栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > Web开发 > JavaScript

layui上传图片到服务器的非项目目录下的方法

JavaScript 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

layui上传图片到服务器的非项目目录下的方法

1、layui没办法与form表单中的其他字段一同提交到后台,所以只能通过先提交图片,然后通过返回的图片的值来提交到数据库

2、先将所需要的jar包导入,我是用的maven所以,需要在父pom.xml文件中添加下面两个jar包(版本自己选择)


  commons-fileupload
  commons-fileupload
  1.3.1


  commons-io
  commons-io
  2.4

3、然后编写前台页面

如果只需要上传一张图片可以看上传logo的步骤,多张的话可以看上传图片的步骤


  
  
    
    
      
      
    
    
    
  


  
  
    
    
      
 
      
      
 
      
    
    
    
  

上图中input和img的目的是为了可以接收返回值,从而在提交时可以将图片信息上传到后台


4、因为layui在上传多张图片的时候是通过多次请求传递过去,所以是数据是一条一条的接收的,如果你需要回显,那么就需要在后台进行拼接,不拼接很可能会出现只传返回一张图片的信息

UploadCollect

@RequestMapping(value = "/uploadImageToServer.do")
@ResponseBody
public ResultMsg insertImageToEducational(@RequestParam(value = "file")MultipartFile[] files) throws Exception {
  ResultMsg msg = new ResultMsg();
  String url = "";
  for (int i=0,length = files.length; i < length; i++) {
    if(files[i] != null && !files[i].isEmpty()) {
      //获取路径,路径我写的是固定路径,直接映射到服务器根目录下的/usr/Images/logo
      String upload_path = IMAGE_ROOT_URL;
      String upload_fileName = FileUpload.uploadFile(files[i], upload_path);
      msg.setStatus(0);
      url = url + upload_fileName;
    }else {
      msg.setStatus(1);
      msg.setMsg("上传失败");
      msg.setUrl("给一个失败的图片路径");
      return msg;
    }
  }
  msg.setStatus(1);
  msg.setMsg("上传成功");
  msg.setUrl(url);
  return msg;

}

FileUpload

public static String uploadFile(MultipartFile multipartFile, String path) throws Exception {
  File file = new File(path);
  if (!file.exists()) {
    file.mkdirs();
  }
  FileInputStream fileInputStream = (FileInputStream) multipartFile.getInputStream();
  String fileName = UUID.randomUUID() + multipartFile.getOriginalFilename();
  BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(path + File.separator + fileName));
  byte[] bs = new byte[1024];
  int len;
  while ((len = fileInputStream.read(bs)) != -1) {
    bos.write(bs, 0, len);
  }
  bos.flush();
  bos.close();
  return fileName;
}

5、这就是图片上传的步骤

以上这篇layui上传图片到服务器的非项目目录下的方法就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持考高分网。

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/73317.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号