Spring Boot文件上傳
文件上傳是項(xiàng)目開(kāi)發(fā)中的常見(jiàn)操作。一般分為如下幾種解決方案
- 直接上傳到應(yīng)用服務(wù)器
- 上傳到阿里云必尼、七牛云等OSS服務(wù)器
- 圖片轉(zhuǎn)成Base64后傳到服務(wù)器
本例以第一種為例,實(shí)現(xiàn)將本地圖片上傳到服務(wù)器指定路徑的基礎(chǔ)功能
新建一個(gè)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目錄下建兩個(gè)html文件缅阳,如圖所示的項(xiàng)目結(jié)構(gòu)
application.properties配置一下上傳參數(shù)
spring.servlet.multipart.max-file-size=100MB
spring.servlet.multipart.max-request-size=100MB
編寫UploadController磕蛇,映射上傳請(qǐng)求
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", "請(qǐng)選擇一個(gè)文件");
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 - 文件上傳狀態(tài)</h1>
<div th:if="${message}">
<h2 th:text="${message}"/>
</div>
</body>
</html>
運(yùn)行啟動(dòng)主類,http://localhost:8080定向到了upload.html頁(yè)面
選擇一個(gè)本地文件,點(diǎn)擊提交秀撇,將文件提交到了服務(wù)器指定目錄超棺,頁(yè)面跳轉(zhuǎn)到upload_status.html,提示上傳成功
image.png
如果要把上傳的路徑跟著項(xiàng)目捌袜,如在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", "請(qǐng)選擇一個(gè)文件");
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";
}
}
會(huì)將文件上傳到target/classes/static目錄下,如圖