![9caeb2a793cae46bd410a99cbee279ee.png](https://img-blog.csdnimg.cn/img_convert/9caeb2a793cae46bd410a99cbee279ee.png)
本文介绍如何在Spring Boot Web应用程序中上传文件。
使用的工具 :
- Spring Boot 1.4.3.RELEASE
- Spring 4.3.5.RELEASE
- Thymeleaf
- Maven 3
- Embedded Tomcat 8.5.6
1. 项目结构
标准项目结构如下图所示 -
![a861ea5945950a85f6e4da49d7f6e2f4.png](https://img-blog.csdnimg.cn/img_convert/a861ea5945950a85f6e4da49d7f6e2f4.png)
2. 项目依赖
Spring boot依赖关系,无需额外的文件上传库。
4.0.0com.felix spring-boot-file-upload jar1.0org.springframework.boot spring-boot-starter-parent 1.4.3.RELEASE1.8org.springframework.boot spring-boot-starter-thymeleaf org.springframework.boot spring-boot-devtools trueorg.springframework.boot spring-boot-maven-plugin
3.文件上传示例
Spring Boot文件上传,不需要什么特别的配置。在Controller中,将上传的文件映射到MultipartFile。
文件:UploadController.java -
package com.felix.controller;import org.springframework.stereotype.Controller;import org.springframework.web.bind.annotation.GetMapping;import org.springframework.web.bind.annotation.PostMapping;import org.springframework.web.bind.annotation.RequestParam;import org.springframework.web.multipart.MultipartFile;import org.springframework.web.servlet.mvc.support.RedirectAttributes;import java.io.IOException;import java.nio.file.Files;import java.nio.file.Path;import java.nio.file.Paths;@Controllerpublic class UploadController { //Save the uploaded file to this folder private static String UPLOADED_FOLDER = "D://temp//"; @GetMapping("/") public String index() { return "upload"; } @PostMapping("/upload") // //new annotation since 4.3 public String singleFileUpload(@RequestParam("file") MultipartFile file, RedirectAttributes redirectAttributes) { if (file.isEmpty()) { redirectAttributes.addFlashAttribute("message