这篇文章主要介绍,如何在springboot工程作为服务器,去接收通过http 上传的multi-file的文件。
构建工程
为例创建一个springmvc工程你需要spring-boot-starter-thymeleaf和 spring-boot-starter-web的起步依赖。为例能够上传文件在服务器,你需要在web.xml中加入
1 | <dependencies> |
创建文件上传controller
直接贴代码:
1 |
|
这个类通过@Controller注解,表明自己上一个Spring mvc的c。每个方法通过
@GetMapping 或者@PostMapping注解表明自己的 http方法。
- GET / 获取已经上传的文件列表
- GET /files/{filename} 下载已经存在于服务器的文件
- POST / 上传文件给服务器
创建一个简单的 html模板
为了展示上传文件的过程,我们做一个界面:
在src/main/resources/templates/uploadForm.html
1 | <html xmlns:th="http://www.thymeleaf.org"> |
上传文件大小限制
如果需要限制上传文件的大小也很简单,只需要在springboot 工程的src/main/resources/application.properties 加入以下:
1 | spring.http.multipart.max-file-size=128KB |
测试
测试情况如图:
参考资料
https://spring.io/guides/gs/uploading-files/
源码下载
https://github.com/forezp/SpringBootLearning
优秀文章推荐:
- 更多springboot 教程:springBoot非官方教程 | 文章汇总
- 更多springcoud 教程:史上最简单的 SpringCloud 教程 | 文章汇总