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

springboot实现多文件上传功能

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

springboot实现多文件上传功能

本文实现springboot的多文件上传,首先创建一个springboot项目,添加spring-boot-starter-web依赖。

然后在resources下的static文件夹下创建uploads.html文件,文件内容如下:




  
  多文件上传




然后编写Controller类

@RestController
public class FilesUploadController {
 
  SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd/");
 
  @RequestMapping("/uploads")
  public String upload(MultipartFile[] uploadFiles, HttpServletRequest request) {
    List list = new ArrayList();//存储生成的访问路径
    if (uploadFiles.length > 0) {
      for (int i = 0; i < uploadFiles.length; i++) {
 MultipartFile uploadFile = uploadFiles[i];
 //设置上传文件的位置在该项目目录下的uploadFile文件夹下,并根据上传的文件日期,进行分类保存
 String realPath = request.getSession().getServletContext().getRealPath("uploadFile");
 String format = sdf.format(new Date());
 File folder = new File(realPath + format);
 if (!folder.isDirectory()) {
   folder.mkdirs();
 }
 
 String oldName = uploadFile.getOriginalFilename();
 System.out.println("oldName = " + oldName);
 String newName = UUID.randomUUID().toString() + oldName.
     substring(oldName.lastIndexOf("."), oldName.length());
 System.out.println("newName = " + newName);
 try {
   //保存文件
   uploadFile.transferTo(new File(folder, newName));
 
   //生成上传文件的访问路径
   String filePath = request.getScheme() + "://" + request.getServerName() + ":"+ request.getServerPort() + "/uploadFile" + format + newName;
   list.add(filePath);
 } catch (IOException e) {
   e.printStackTrace();
 }
      }
      return list.toString();
    } else if (uploadFiles.length == 0) {
      return "请选择文件";
    }
    return "上传失败";
  }
}

相比于单文件上传,这里就多了一个遍历的过程。

文件上传常见配置:

#是否开启文件上传支持,默认是true
spring.servlet.multipart.enabled=true 
#文件写入磁盘的阈值,默认是0
spring.servlet.multipart.file-size-threshold=0
#上传文件的临时保存位置
spring.servlet.multipart.location=D:\upload
#单个文件的最大值,默认是1MB
spring.servlet.multipart.max-file-size=1MB
#多个文件上传时的总大小 值,默认是10MB
spring.servlet.multipart.max-request-size=10MB
#是否延迟解析,默认是false
spring.servlet.multipart.resolve-lazily=false

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持考高分网。

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

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

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