上传文件是我们java开发的基本操作,在这里我向大家展示下spring boot 项目的文件上传

1.springboot 默认文件上传设置

根据不同版本,对应的设置值不一样

Spring Boot 1.3.x and earlier
            multipart.maxFileSize
            multipart.maxRequestSize
Spring Boot 1.4.x and 1.5.x
            spring.http.multipart.maxFileSize
            spring.http.multipart.maxRequestSize
Spring Boot 2.x
            spring.servlet.multipart.maxFileSize
            spring.servlet.multipart.maxRequestSize

我使用的 2.0 所以我的配置是这样的:

# 上传文件大小限制
spring.servlet.multipart.max-file-size=100MB
spring.servlet.multipart.max-request-size=100MB

2.我在properties 文件里面自定义了 文件上传的存储路径

# 自定义上传文件存储路径
web.uploadpath:D:/webupload/

3.前端html的编写,这个比较基础,就直接放代码了

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>zhangzq</title>
</head>
<body>
    <h1>upload file</h1>
    <form action="/upload" method="post" enctype="multipart/form-data" >
        <p><span>文件:</span><input type="file" name="basefile" /></p>
        <p><span>描述:</span><input type="text" name="desc" /></p>
        <p><input type="submit" value="提交" ></p>
    </form>
</body>
</html>

4.webupload controller 的编写

首先 使用

@Value("${web.uploadpath}")
private String path;

将自定义的 存储路径注入到 path 属性中去。

然后使用 

MultipartFile file接收上传的文件信息,注意这里的名字和 前端name 的一样。

如果这里实在不能做到统一,则使用 

@RequestParam("basefile") MultipartFile file 转一下也是可以的。

然后就是 io读写了

看看代码吧:

@Controller
public class WebUpload {

    @Value("${web.uploadpath}")
    private String path;

    @RequestMapping("/upload")
    @ResponseBody
    public Map<String , Object> update(@RequestParam("basefile") MultipartFile file , String desc){
        Map<String , Object> result = new HashMap<>();
        try {
            System.out.println( "文件名:" + file.getOriginalFilename() );
            System.out.println( "描述:" + desc + "<====>" + path );

            String filepath = path + System.currentTimeMillis()+ "_" + file.getOriginalFilename();
            BufferedInputStream bis = new BufferedInputStream( file.getInputStream() );
            BufferedOutputStream bos = new BufferedOutputStream( new FileOutputStream( new File( filepath ) ));

            byte [] data = new byte[1024];
            int len = 0;
            while( (len=bis.read(data)) != -1 ){
                bos.write(data , 0 ,len);
            }
            bos.flush();
            bos.close();
            bis.close();

            result.put("fileSavePath",filepath);
            result.put("desc",desc);
            result.put("status",true);
            return result;
        } catch (Exception e) {
            e.printStackTrace();
            result.put("status",false);
            return result;
        }
    }
}

 

运行效果:

SpringBoot之上传文件

相关文章: