转载请标明出处:

原文首发于: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非官方教程 | 第十七篇:上传文件的更多相关文章

  1. (转)SpringBoot非官方教程 | 第七篇:springboot开启声明式事务

    springboot开启事务很简单,只需要一个注解@Transactional 就可以了.因为在springboot中已经默认对jpa.jdbc.mybatis开启了事事务,引入它们依赖的时候,事物就 ...

  2. SpringBoot非官方教程 | 第二十三篇: 异步方法

    转载请标明出处: 原文首发于https://www.fangzhipeng.com/springboot/2017/07/11/springboot-ansy/ 本文出自方志朋的博客 这篇文章主要介绍 ...

  3. (转)SpringBoot非官方教程 | 第三篇:SpringBoot用JdbcTemplates访问Mysql

    本文介绍springboot通过jdbc访问关系型MySQL,通过spring的JdbcTemplate去访问. 准备工作 jdk 1.8 maven 3.0 idea mysql 初始化mysql: ...

  4. 基于spring-boot的web应用,ckeditor上传文件图片文件

    说来惭愧,这个应用调试,折腾了我一整天,google了很多帖子,才算整明白,今天在这里做个记录和分享吧,也作为自己后续的参考! 第一步,ckeditor(本博文论及的ckeditor版本4.5.6)的 ...

  5. SpringBoot项目打成jar包后上传文件到服务器 目录与jar包同级问题

    看标题好像很简单的样子,但是针对使用jar包发布SpringBoot项目就不一样了.当你使用tomcat发布项目的时候,上传文件存放会变得非常简单,因为你可以随意操作项目路径下的资源.但是当你使用Sp ...

  6. springboot 项目打包部署后设置上传文件访问的绝对路径

    1.设置绝对路径 application.properties的配置 #静态资源对外暴露的访问路径 file.staticAccessPath=/upload/** #文件上传目录(注意Linux和W ...

  7. FastAPI 学习之路(十七)上传文件

    系列文章: FastAPI 学习之路(一)fastapi--高性能web开发框架 FastAPI 学习之路(二) FastAPI 学习之路(三) FastAPI 学习之路(四) FastAPI 学习之 ...

  8. SpringBoot非官方教程 | 第十三篇:springboot集成spring cache

    转载请标明出处: 原文首发于:https://www.fangzhipeng.com/springboot/2017/07/11/springboot13-springcache/ 本文出自方志朋的博 ...

  9. SpringBoot非官方教程 | 第七篇:springboot开启声明式事务

    转载请标明出处: http://blog.csdn.net/forezp/article/details/70833629 本文出自方志朋的博客 springboot开启事务很简单,只需要一个注解@T ...

随机推荐

  1. 6、Modal

    1.首先Modal是一个内容窗格.通常用来做一个选择或编辑. 先来看一下 tabs.html 做了什么. /* --- tabs.html ----*/ <ion-navbar *navbar ...

  2. C#基础知识-引用类型和值类型的区别(六)

    在第一篇中我们介绍了C#中基本的15种数据类型,这15种数据类型中又分为两大类,一种是值类型,一种是引用类型.值类型有sbyte.short.long.int.byte.ushort.uint.ulo ...

  3. nginx配置文件分开配置

    在Linux中不同的用户都可能用到Nginx,如果不同的用户无法达成一个对nginx.conf编写标准,势必会导致nginx.conf里的内容变的相当混乱,极难维护.所以这里建议新建一个文件夹,这个文 ...

  4. JavaWeb技术

    1.简介 Java Web是用Java技术来解决相关web互联网领域的技术总和.web包括:web服务器和web客户端两部分.Java在客户端的应用有java applet,不过使用得很少,Java在 ...

  5. 可编辑DIV 光标位置 处理

    //场景: 要做一个网页即时通信,发送信息的文本编辑框 要求能发图片和表情,那么textarea就不能满足需求了,因为textarea内没有办法加入image // 采用方案是使用可编辑的DIV(也就 ...

  6. linux环境下 mysql数据库忘记密码 处理办法

    整个修改过程大概3-10分钟(看个人操作),这个时间内mysql出于不需要密码就能登陆的状态,请设法保证系统安全 不罗嗦直接上步骤 1.vi /etc/my.cnf 在[mysqld]下,添加一句:s ...

  7. js中实现多态

    最近读到一本书<JavaScript设计模式与开发实践>上,讲到js的多态,我在JavaScript高级程序编程里貌似都没有见过关于这个的详细讲解,所以想问问大家有没有什么推荐的文章或者博 ...

  8. 从软件工程师的角度看MacBook Air的几个设计亮点

    我多年从事软件开发和运营工作,从未跟“设计”间断过.现在在设计一个全新saas产品:超级表格(www.domypp.com).最近买了台苹果最新款的笔记本电脑MacBook Air,从该产品功能设计和 ...

  9. qt打开url

    QDesktopServices::openUrl(QUrl(QLatin1String(“http://blog.const.net.cn“)))

  10. liunx增强命令

    查找命令 grep 格式:grep [option] pattern [file] 实例: ps -ef | grep sshd 查找指定 ssh 服务进程 ps -ef | grep sshd | ...