SpringBoot 文件上传代码

HTML页面

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<form action="/upload" method="post" enctype="multipart/form-data">
    <input type="file" name="uploadFile" value="请选择文件" multiple>
    <input type="submit" value="上传">
</form>
</body>
</html>

控制器代码


	//单文件上传
 	@PostMapping("/upload")
    @ResponseBody
    public List upload(MultipartFile uploadFile, HttpServletRequest request) {
        return saveFile(request, uploadFile);
    }
    
	//多文件上传
    @PostMapping("/uploads")
    @ResponseBody
    public List uploads(MultipartFile[] uploadFiles, HttpServletRequest request) {
        return saveFile(request, uploadFiles);
    }

	//文件上传
    public List saveFile(HttpServletRequest request, MultipartFile... uploadFiles) {
        String realPath = request.getSession().getServletContext().getRealPath("/uploadFile");
        List<String> paths = new ArrayList<>();
        for (MultipartFile uploadFile : uploadFiles) {
            String format = sdf.format(new Date());
            File folder = new File(realPath + format);
            if (!folder.isDirectory()) {
                System.out.println(realPath);
                System.out.println(folder);
                folder.mkdirs();
            }
            String oldName = uploadFile.getOriginalFilename();
            String newName = UUID.randomUUID().toString() + oldName.substring(oldName.lastIndexOf("."), oldName.length());
            try {
                uploadFile.transferTo(new File(folder, newName));
                paths.add(request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + "/uploadFile" + format + newName);
            } catch (IOException e) {
                e.printStackTrace();
                paths.add(oldName + "上传失败!");
            }
        }
        return paths;
    }

application.properties文件配置如下

1 spring.servlet.multipart.enabled=true
2 spring.servlet.multipart.file-size-threshold=0
3 spring.servlet.multipart.location=E:\\temp
4 spring.servlet.multipart.max-file-size=1MB
5 spring.servlet.multipart.max-request-size=10MB
6 spring.servlet.multipart.resolve-lazily=false

● 第1行表示是否开启文件上传支持,默认为true.
● 第2行表示文件写入磁盘的阈值,默认为0。
● 第3行表示,上传文件的临时保存位置。
● 第4行表示.上传的单个文件的最大大小,默认为1MB.
● 第5行表示多文件,上传时文件的总大小,默认为10MB.
● 第6行表示文件是否延迟解析,默认为false.
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值