上傳方式:
- 直接上傳到應(yīng)用服務(wù)器
- 上傳到css(阿里云、七牛云)
- 前端將圖片轉(zhuǎn)成Base64編碼上傳
http://localhost:8080/
SpringBoot文件上傳示例——前后端不分離
新建模塊
image
1.upload.html頁面
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Spring Boot文件上傳頁面</title>
</head>
<body>
<form method="post" action="/upload" enctype="multipart/form-data">
<input type="file" name="file">
<input type="submit" value="上傳">
</form>
</body>
</html>
表單 action /upload
/upload_status
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>文件上傳狀態(tài)顯示</title>
</head>
<body>
<h2>Spring Boot的文件上傳狀態(tài)</h2>
<div th:if="${message}">
<h2 th:text="${message}"></h2>
</div>
</body>
</html>
2.添加web碱妆、thymeleaf依賴
<dependencies>
<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>
3.配置上傳屬性application.properties肉盹,指定上傳文件大小限制等
#文件上傳的配置
spring.servlet.multipart.max-file-size=100MB
4.編寫Controller,通過java.nio實(shí)現(xiàn)穩(wěn)健的上傳
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;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;
/**
* 上傳文件控制器
* 直接上傳到服務(wù)器
*
*/
@Controller
public class UploadController {
//指定一個(gè)臨時(shí)路徑作為上傳目錄
//private static String UPLOAD_FOLDER = "C:\\Users\\Liuyu\\Desktop\\UPLOAD\\";
//遇到http://localhost:8080疹尾,則跳轉(zhuǎn)至upload.html頁面
@GetMapping("/")
public String index() {
return "upload";
}
@PostMapping("upload")
public String fileUpload(@RequestParam("file")MultipartFile srcFile, RedirectAttributes redirectAttributes) {
//前端沒有選擇文件上忍,srcFile為空
if(srcFile.isEmpty()) {
redirectAttributes.addFlashAttribute("message", "請(qǐng)選擇一個(gè)文件");
return "redirect:upload_status";
}
//選擇了文件,開始上傳操作
try {
//構(gòu)建上傳目標(biāo)路徑纳本,找到了項(xiàng)目的target的classes目錄
File destFile = new File(ResourceUtils.getURL("classpath:").getPath());
if(!destFile.exists()) {
destFile = new File("");
}
//輸出目標(biāo)文件的絕對(duì)路徑
System.out.println("file path:"+destFile.getAbsolutePath());
//拼接子路徑
SimpleDateFormat sf_ = new SimpleDateFormat("yyyyMMddHHmmss");
String times = sf_.format(new Date());
File upload = new File(destFile.getAbsolutePath(), "static/"+times);
//若目標(biāo)文件夾不存在窍蓝,則創(chuàng)建
if(!upload.exists()) {
upload.mkdirs();
}
System.out.println("完整的上傳路徑:"+upload.getAbsolutePath()+"/"+srcFile);
//根據(jù)srcFile大小,準(zhǔn)備一個(gè)字節(jié)數(shù)組
byte[] bytes = srcFile.getBytes();
//拼接上傳路徑
//Path path = Paths.get(UPLOAD_FOLDER + srcFile.getOriginalFilename());
//通過項(xiàng)目路徑饮醇,拼接上傳路徑
Path path = Paths.get(upload.getAbsolutePath()+"/"+srcFile.getOriginalFilename());
//** 開始將源文件寫入目標(biāo)地址
Files.write(path, bytes);
String uuid = UUID.randomUUID().toString().replaceAll("-", "");
// 獲得文件原始名稱
String fileName = srcFile.getOriginalFilename();
// 獲得文件后綴名稱
String suffixName = fileName.substring(fileName.lastIndexOf(".") + 1).toLowerCase();
// 生成最新的uuid文件名稱
String newFileName = uuid + "."+ suffixName;
redirectAttributes.addFlashAttribute("message", "文件上傳成功"+newFileName);
} catch (IOException e) {
e.printStackTrace();
}
return "redirect:upload_status";
}
//匹配upload_status頁面
@GetMapping("upload_status")
public String uploadStatusPage() {
return "upload_status";
}
}
5.運(yùn)行項(xiàng)目它抱,上傳文件,結(jié)果
image
image
6.也可以將項(xiàng)目打成jar包朴艰,輸入控制臺(tái)命令"java -jar XXX"(XXX代表jar包名)观蓄,運(yùn)行成功之后在瀏覽器輸入:http://localhost:8080,可以和第8點(diǎn)得到同樣的結(jié)果
刪除 target 目錄祠墅,一定要停止運(yùn)行剛才在Application中的運(yùn)行(否則運(yùn)行失斘甏)
-
點(diǎn)擊右側(cè)Maven目錄,找到upload項(xiàng)目的Lifecycle毁嗦,依次雙擊 clean 和 install 亲茅,出現(xiàn) "BUILD SUCCESS" 成功
imageimage -
復(fù)制target目錄下的 .jar 文件到任意目錄
image -
運(yùn)行:http://localhost:8080,運(yùn)行成功如下
image
- 在jar的同級(jí)目錄下會(huì)創(chuàng)建 static 文件夾來存放上傳的文件