SpringBoot非官方教程 | 第十七篇:上传文件
转载请标明出处:
原文首发于:https://www.fangzhipeng.com/springboot/2017/07/11/springboot14-upload/
本文出自方志朋的博客
这篇文章主要介绍,如何在springboot工程作为服务器,去接收通过http 上传的multi-file的文件。
构建工程
为例创建一个springmvc工程你需要spring-boot-starter-thymeleaf和 spring-boot-starter-web的起步依赖。为例能够上传文件在服务器,你需要在web.xml中加入标签做相关的配置,但在sringboot 工程中,它已经为你自动做了,所以不需要你做任何的配置。
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
</dependencies>
创建文件上传controller
直接贴代码:
@Controller
public class FileUploadController {
private final StorageService storageService;
@Autowired
public FileUploadController(StorageService storageService) {
this.storageService = storageService;
}
@GetMapping("/")
public String listUploadedFiles(Model model) throws IOException {
model.addAttribute("files", storageService
.loadAll()
.map(path ->
MvcUriComponentsBuilder
.fromMethodName(FileUploadController.class, "serveFile", path.getFileName().toString())
.build().toString())
.collect(Collectors.toList()));
return "uploadForm";
}
@GetMapping("/files/{filename:.+}")
@ResponseBody
public ResponseEntity<Resource> serveFile(@PathVariable String filename) {
Resource file = storageService.loadAsResource(filename);
return ResponseEntity
.ok()
.header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\""+file.getFilename()+"\"")
.body(file);
}
@PostMapping("/")
public String handleFileUpload(@RequestParam("file") MultipartFile file,
RedirectAttributes redirectAttributes) {
storageService.store(file);
redirectAttributes.addFlashAttribute("message",
"You successfully uploaded " + file.getOriginalFilename() + "!");
return "redirect:/";
}
@ExceptionHandler(StorageFileNotFoundException.class)
public ResponseEntity handleStorageFileNotFound(StorageFileNotFoundException exc) {
return ResponseEntity.notFound().build();
}
}
这个类通过@Controller注解,表明自己上一个Spring mvc的c。每个方法通过
@GetMapping 或者@PostMapping注解表明自己的 http方法。
- GET / 获取已经上传的文件列表
- GET /files/{filename} 下载已经存在于服务器的文件
- POST / 上传文件给服务器
创建一个简单的 html模板
为了展示上传文件的过程,我们做一个界面:
在src/main/resources/templates/uploadForm.html
<html xmlns:th="http://www.thymeleaf.org">
<body>
<div th:if="${message}">
<h2 th:text="${message}"/>
</div>
<div>
<form method="POST" enctype="multipart/form-data" action="/">
<table>
<tr><td>File to upload:</td><td><input type="file" name="file" /></td></tr>
<tr><td></td><td><input type="submit" value="Upload" /></td></tr>
</table>
</form>
</div>
<div>
<ul>
<li th:each="file : ${files}">
<a th:href="${file}" th:text="${file}" />
</li>
</ul>
</div>
</body>
</html>
上传文件大小限制
如果需要限制上传文件的大小也很简单,只需要在springboot 工程的src/main/resources/application.properties 加入以下:
spring.http.multipart.max-file-size=128KB
spring.http.multipart.max-request-size=128KB
测试
测试情况如图:
参考资料
https://spring.io/guides/gs/uploading-files/
源码下载
https://github.com/forezp/SpringBootLearning
扫码关注公众号有惊喜
(转载本站文章请注明作者和出处 方志朋的博客)
SpringBoot非官方教程 | 第十七篇:上传文件的更多相关文章
- (转)SpringBoot非官方教程 | 第七篇:springboot开启声明式事务
springboot开启事务很简单,只需要一个注解@Transactional 就可以了.因为在springboot中已经默认对jpa.jdbc.mybatis开启了事事务,引入它们依赖的时候,事物就 ...
- SpringBoot非官方教程 | 第二十三篇: 异步方法
转载请标明出处: 原文首发于https://www.fangzhipeng.com/springboot/2017/07/11/springboot-ansy/ 本文出自方志朋的博客 这篇文章主要介绍 ...
- (转)SpringBoot非官方教程 | 第三篇:SpringBoot用JdbcTemplates访问Mysql
本文介绍springboot通过jdbc访问关系型MySQL,通过spring的JdbcTemplate去访问. 准备工作 jdk 1.8 maven 3.0 idea mysql 初始化mysql: ...
- 基于spring-boot的web应用,ckeditor上传文件图片文件
说来惭愧,这个应用调试,折腾了我一整天,google了很多帖子,才算整明白,今天在这里做个记录和分享吧,也作为自己后续的参考! 第一步,ckeditor(本博文论及的ckeditor版本4.5.6)的 ...
- SpringBoot项目打成jar包后上传文件到服务器 目录与jar包同级问题
看标题好像很简单的样子,但是针对使用jar包发布SpringBoot项目就不一样了.当你使用tomcat发布项目的时候,上传文件存放会变得非常简单,因为你可以随意操作项目路径下的资源.但是当你使用Sp ...
- springboot 项目打包部署后设置上传文件访问的绝对路径
1.设置绝对路径 application.properties的配置 #静态资源对外暴露的访问路径 file.staticAccessPath=/upload/** #文件上传目录(注意Linux和W ...
- FastAPI 学习之路(十七)上传文件
系列文章: FastAPI 学习之路(一)fastapi--高性能web开发框架 FastAPI 学习之路(二) FastAPI 学习之路(三) FastAPI 学习之路(四) FastAPI 学习之 ...
- SpringBoot非官方教程 | 第十三篇:springboot集成spring cache
转载请标明出处: 原文首发于:https://www.fangzhipeng.com/springboot/2017/07/11/springboot13-springcache/ 本文出自方志朋的博 ...
- SpringBoot非官方教程 | 第七篇:springboot开启声明式事务
转载请标明出处: http://blog.csdn.net/forezp/article/details/70833629 本文出自方志朋的博客 springboot开启事务很简单,只需要一个注解@T ...
随机推荐
- ubuntu遇到了 dpkg was interrupted, you must manually run 'dpkg..的问题
dpkg was interrupted, you must manually run 'dpkg --configure -a' to correct the problem. E: _cache- ...
- html结构内容拾忆
文本格式化: <b>This text is bold</b><!--定义粗体文本.--> <strong>This text is strong< ...
- Unity3D第二课之通过键盘、鼠标移动物体
public class xuanzhuan : MonoBehaviour { //平移速度变量 public float MoveSpeed;// Use this for initializat ...
- javaSE练习1——变量和运算符
一.已知a,b均是整型变量,写出将a,b两个变量中的值互换的程序.(知识点:变量和运算符综合应用): package com.test; public class t01 { public stati ...
- sublime text 3 添加代码片段
工具>插件开发>新建代码片段 <snippet> <content> <![CDATA[ Hello, ${1:this} is a ${2:snippet} ...
- webstrom 在脚本区域写其他语言得到语法提示
webstrom 在脚本区域写其他语言得到语法提示 webstrom 的提示小灯泡 点击inject language or reference 选择相应的语言. 如果写的内容比较多, 可以按照web ...
- 详解Struts1.x的运行机制及命名规则
Struts1.x 调用一个action的大致流程: 1)首先前端发送 *.do的一个action请求(通过点击表单提交按钮,js 事件等): 2)web.xml 文件通过 *.do 找到 Actio ...
- angular.uirouter
首先给大家介绍angular-ui-router的基本用法.如何引用依赖angular-ui-router angular.module('app',["ui.router"]). ...
- 【NLP_Stanford课堂】最小编辑距离
一.什么是最小编辑距离 最小编辑距离:是用以衡量两个字符串之间的相似度,是两个字符串之间的最小操作数,即从一个字符转换成另一个字符所需要的操作数,包括插入.删除和置换. 每个操作数的cost: 每个操 ...
- Oracle里删除重复记录,保留一项
我们在使用数据库的时候,有时数据会有所重复,当我们只需要一项数据时,不需要显示重复的记录时 如下就有SQL代码: --查找表中多余的重复记录,重复记录是根据单个字段来判断 select * from ...