springboot实现多文件上传

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

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

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>多文件上传</title>
</head>
<body>
<form action="/uploads" method="post"  enctype="multipart/form-data">
    <input type="file" name="uploadFiles" value="请选择文件" multiple>
    <input type="submit" value="上传">
</form>
</body>
</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

🐞标题:springboot实现多文件上传
👽作者:ruige
🐾地址:https://jjdhhc.com/articles/2020/11/07/1604719623738.html
🙏感恩:谢谢您的打赏与支持!中间图片是我的微信公众号,扫码关注哦!
支付宝支付 微信公众号 微信支付