Spring Boot文件上传
文件上传是项目开发中的常见操作。一般分为如下几种解决方案
- 直接上传到应用服务器
- 上传到阿里云、七牛云等OSS服务器
- 图片转成Base64后传到服务器
本例以第一种为例,实现将本地图片上传到服务器指定路径的基础功能
新建一个module,命名为file-upload,勾选web、Thymeleaf依赖
pom.xml
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
<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>
在resources的templates目录下建两个html文件,如图所示的项目结构
image.png
application.properties配置一下上传参数
spring.servlet.multipart.max-file-size=100MB
spring.servlet.multipart.max-request-size=100MB
编写UploadController,映射上传请求
package com.springboot.fileupload.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;
@Controller
public class UploadController {
private static String UPLOADED_FOLDER = "E:/temp/";
@GetMapping("/")
public String index() {
return "upload";
}
@PostMapping("/upload")
public String singleFileUpload(@RequestParam("file") MultipartFile file,
RedirectAttributes redirectAttributes) {
if (file.isEmpty()) {
redirectAttributes.addFlashAttribute("message", "请选择一个文件");
return "redirect:upload_status";
}
try {
byte[] bytes = file.getBytes();
Path path = Paths.get(UPLOADED_FOLDER + file.getOriginalFilename());
Files.write(path, bytes);
redirectAttributes.addFlashAttribute("message",
"文件成功上传!" + file.getOriginalFilename());
} catch (IOException e) {
e.printStackTrace();
}
return "redirect:/upload_status";
}
@GetMapping("/upload_status")
public String uploadStatus() {
return "upload_status";
}
}
upload.html文件
<!DOCTYPE html>
<html lang="en">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1,user-scalable=no">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<body>
<h1>Spring Boot 文件上传示例</h1>
<form method="POST" action="/upload" enctype="multipart/form-data">
<input type="file" name="file"/>
<br>
<br>
<input type="submit" value="提交"/>
</form>
</body>
</html>
upload_status.html文件
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<body>
<h1>Spring Boot - 文件上传状态</h1>
<div th:if="${message}">
<h2 th:text="${message}"/>
</div>
</body>
</html>
运行启动主类,http://localhost:8080定向到了upload.html页面
image.png选择一个本地文件,点击提交,将文件提交到了服务器指定目录,页面跳转到upload_status.html,提示上传成功
image.png
image.png
image.png
如果要把上传的路径跟着项目,如在static目录下的upload文件夹,则需要更改UploadController代码
import org.springframework.stereotype.Controller;
import org.springframework.util.ResourceUtils;
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.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
@Controller
public class UploadController {
@GetMapping("/")
public String index() {
return "upload";
}
@PostMapping("/upload")
public String singleFileUpload(@RequestParam("file") MultipartFile srcFile,
RedirectAttributes redirectAttributes) {
if (srcFile.isEmpty()) {
redirectAttributes.addFlashAttribute("message", "请选择一个文件");
return "redirect:upload_status";
}
try {
File destFile = new File(ResourceUtils.getURL("classpath:").getPath());
if (!destFile.exists()) {
destFile = new File("");
}
System.out.println("file path:" + destFile.getAbsolutePath());
File upload = new File(destFile.getAbsolutePath(), "static/");
if (!upload.exists()) {
upload.mkdirs();
}
System.out.println("upload url:" + upload.getAbsolutePath());
Path path = Paths.get(upload.getAbsolutePath() + "/" + srcFile.getOriginalFilename());
byte[] bytes = srcFile.getBytes();
Files.write(path, bytes);
redirectAttributes.addFlashAttribute("message",
"文件成功上传!" + srcFile.getOriginalFilename());
} catch (IOException e) {
e.printStackTrace();
}
return "redirect:/upload_status";
}
@GetMapping("/upload_status")
public String uploadStatus() {
return "upload_status";
}
}
会将文件上传到target/classes/static目录下,如图
image.png
网友评论