SpringBoot文件上傳功能的實(shí)現(xiàn)方法
1.應(yīng)用實(shí)例
需求: 演示 Spring-Boot 通過(guò)表單注冊(cè)用戶,并支持上傳圖片
2.代碼實(shí)現(xiàn)
代碼實(shí)現(xiàn)-文件上傳
創(chuàng)建 templates/upload.html , 要求頭像只能選擇一個(gè), 而寵物可以上傳多個(gè)圖片
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>upload</title>
</head>
<body bgcolor="#CED3FE">
<img src="images/1.GIF"/>
<hr/>
<div style="text-align: center">
<h1>注冊(cè)用戶~</h1>
<form action="#" th:action="@{/upload}" method="post" enctype="multipart/form-data">
用戶名:<input type="text" style="width:150px" name="name"/><br/><br/>
電 郵:<input type="text" style="width:150px" name="email"/><br/><br/>
年 齡:<input type="text" style="width:150px" name="age"/><br/><br/>
職 位:<input type="text" style="width:150px" name="job"/><br/><br/>
頭 像:<input type="file" style="width:150px" name="header"><br/><br/>
寵 物:<input type="file" style="width:150px" name="photos" multiple><br/><br/>
<input type="submit" value="注冊(cè)"/>
<input type="reset" value="重新填寫"/>
</form>
</div>
<hr/>
</body>
</html>2.創(chuàng)建src\main\java\com\llp\springboot\controller\UploadController.java
@Slf4j
@Controller
public class UploadController {
//處理轉(zhuǎn)發(fā)到用戶注冊(cè)-可以完成文件上傳頁(yè)面
@GetMapping("/upload.html")
public String uploadPage() {
return "upload";// 視圖解析,轉(zhuǎn)發(fā)到templates/upload.html
}
@PostMapping("/upload")
@ResponseBody
public String upload(@RequestParam("name") String name,
@RequestParam("email") String email,
@RequestParam("age") Integer age,
@RequestParam("job") String job,
@RequestParam("header") MultipartFile header,
@RequestParam("photos") MultipartFile[] photos) throws IOException {
log.info("name:{},email:{},age:{},job:{},header.size:{},photos.length:{}",name,email,age,job,header.getSize(),photos.length);
//1.獲取源文件名稱
String originalFilename = header.getOriginalFilename();
// /E:/IdeaProjects/springboot-sysuser/target/classes/
String path = ResourceUtils.getURL("classpath:").getPath();
System.out.println(path);
File file = new File(path+"static/images/upload/");
if(!file.exists()){
file.mkdirs();
}
header.transferTo(new File(path+"static/images/upload/"+originalFilename));
return "注冊(cè)用戶成功/文件上傳成功";
}
}

3.引出兩個(gè)問(wèn)題
1.文件覆蓋問(wèn)題
上面的示例中實(shí)現(xiàn)了文件的上傳,但當(dāng)兩個(gè)不同的文件文件名相同時(shí)會(huì)存在文件覆蓋的問(wèn)題,如何解決呢?
@PostMapping("/upload")
@ResponseBody
public String upload(@RequestParam("name") String name,
@RequestParam("email") String email,
@RequestParam("age") Integer age,
@RequestParam("job") String job,
@RequestParam("header") MultipartFile header,
@RequestParam("photos") MultipartFile[] photos) throws IOException {
log.info("name:{},email:{},age:{},job:{},header.size:{},photos.length:{}",name,email,age,job,header.getSize(),photos.length);
//1.獲取源文件名稱
String originalFilename = header.getOriginalFilename();
originalFilename = UUID.randomUUID().toString().replaceAll("-","")+System.nanoTime()+originalFilename;
//2.獲取文件上傳的路徑
// /E:/IdeaProjects/springboot-sysuser/target/classes/
String path = ResourceUtils.getURL("classpath:").getPath();
System.out.println(path);
//3.動(dòng)態(tài)的創(chuàng)建文件上傳目錄
File file = new File(path+"static/images/upload/");
if(!file.exists()){
file.mkdirs();
}
//4.將文件傳輸?shù)侥繕?biāo)目錄
header.transferTo(new File(path+"static/images/upload/"+originalFilename));
return "注冊(cè)用戶成功/文件上傳成功";
}originalFilename = UUID.randomUUID().toString().replaceAll("-","")+System.nanoTime()+originalFilename;,實(shí)現(xiàn)思路就是給上傳的文件重新指定一個(gè)不重復(fù)的文件名

2.將文件都上傳到一個(gè)目錄下,當(dāng)上傳文件很多時(shí),會(huì)造成訪問(wèn)文件速度變慢
解決思路:將文件上傳到不同目錄 比如 一天上傳的文件,統(tǒng)一放到 一個(gè)文件夾 年/月/日, 比如 2022/11/11 目錄
public class WebUtils {
//定義一個(gè)文件上傳的路徑
public static String UPLOAD_FILE_DIRECTORY = "static/images/upload/";
//編寫方法,生成一個(gè)目錄-根據(jù)當(dāng)前日期 年/月/日
public static String getUploadFileDirectory() {
return UPLOAD_FILE_DIRECTORY + new SimpleDateFormat("yyyy/MM/dd").format(new Date());
}
}@PostMapping("/upload")
@ResponseBody
public String upload(@RequestParam("name") String name,
@RequestParam("email") String email,
@RequestParam("age") Integer age,
@RequestParam("job") String job,
@RequestParam("header") MultipartFile header,
@RequestParam("photos") MultipartFile[] photos) throws IOException {
//輸出獲取到的信息
log.info("上傳的信息 name={} email={} age={} job={} header={} photos={} ",
name, email, age, job, header.getSize(), photos.length);
//得到類路徑(運(yùn)行的時(shí)候)
String path = ResourceUtils.getURL("classpath:").getPath();
//log.info("path={}", path);
//動(dòng)態(tài)創(chuàng)建指定目錄
File file = new File(path + WebUtils.getUploadFileDirectory());
if (!file.exists()) {//如果目錄不存在,我們就創(chuàng)建, 在java io
file.mkdirs();
}
if (!header.isEmpty()) {//處理頭像
//獲取上傳文件的名字
String originalFilename = header.getOriginalFilename();
String fileName = UUID.randomUUID().toString() + "_" + System.currentTimeMillis() + "_" + originalFilename;
//保存到動(dòng)態(tài)創(chuàng)建的目錄
header.transferTo(new File(file.getAbsolutePath() + "/" + fileName));
}
//處理多個(gè)文件
if (photos.length > 0) {
for (MultipartFile photo : photos) {//遍歷
if (!photo.isEmpty()) {
String originalFilename = photo.getOriginalFilename();
String fileName = UUID.randomUUID().toString() + "_" + System.currentTimeMillis() + "_" + originalFilename;
//保存到動(dòng)態(tài)創(chuàng)建的目錄
photo.transferTo(new File(file.getAbsolutePath() + "/" + fileName));
}
}
}
return "注冊(cè)用戶成功/文件上傳成功";
}
到此這篇關(guān)于SpringBoot文件上傳功能的實(shí)現(xiàn)方法的文章就介紹到這了,更多相關(guān)SpringBoot文件上傳內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
SSH框架網(wǎng)上商城項(xiàng)目第20戰(zhàn)之在線支付平臺(tái)
這篇文章主要為大家詳細(xì)介紹了SSH框架網(wǎng)上商城項(xiàng)目第20戰(zhàn)之在線支付平臺(tái),關(guān)于第三方支付的內(nèi)容從本文開始,感興趣的小伙伴們可以參考一下2016-06-06
SpringSecurity實(shí)現(xiàn)圖形驗(yàn)證碼功能的實(shí)例代碼
Spring Security 的前身是 Acegi Security ,是 Spring 項(xiàng)目組中用來(lái)提供安全認(rèn)證服務(wù)的框架。這篇文章主要介紹了SpringSecurity實(shí)現(xiàn)圖形驗(yàn)證碼功能,需要的朋友可以參考下2018-10-10
spring?cloud?gateway限流常見(jiàn)算法實(shí)現(xiàn)
本文主要介紹了spring?cloud?gateway限流常見(jiàn)算法實(shí)現(xiàn),文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧2025-02-02
SpringBoot統(tǒng)計(jì)接口調(diào)用耗時(shí)的三種方式
在實(shí)際開發(fā)中,了解項(xiàng)目中接口的響應(yīng)時(shí)間是必不可少的事情,SpringBoot 項(xiàng)目支持監(jiān)聽(tīng)接口的功能也不止一個(gè),接下來(lái)我們分別以 AOP、ApplicationListener、Tomcat 三個(gè)方面去實(shí)現(xiàn)三種不同的監(jiān)聽(tīng)接口響應(yīng)時(shí)間的操作,需要的朋友可以參考下2024-06-06
http調(diào)用controller方法時(shí)openfeign執(zhí)行流程
這篇文章主要為大家介紹了http調(diào)用controller方法時(shí)openfeign執(zhí)行流程,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2023-07-07
Spring用三級(jí)緩存處理循環(huán)依賴的方法詳解
這篇文章主要介紹了Spring用三級(jí)緩存處理循環(huán)依賴的方法,在Spring?框架中,依賴注入是其核心特性之一,它允許對(duì)象之間的依賴關(guān)系在運(yùn)行時(shí)動(dòng)態(tài)注入,然而,當(dāng)多個(gè)Bean之間的依賴關(guān)系形成一個(gè)閉環(huán)時(shí),就會(huì)出現(xiàn)循環(huán)依賴問(wèn)題,本文就為解決此問(wèn)題,需要的朋友可以參考下2025-02-02
Java中常見(jiàn)字符串拼接九種方式詳細(xì)例子
這篇文章主要給大家介紹了關(guān)于Java中常見(jiàn)字符串拼接的九種方式,字符串拼接是我們?cè)贘ava代碼中比較經(jīng)常要做的事情,就是把多個(gè)字符串拼接到一起,文中通過(guò)代碼介紹的非常詳細(xì),需要的朋友可以參考下2023-07-07
java_String和StringBuffer區(qū)別分析
JAVA平臺(tái)提供了兩個(gè)類:String和StringBuffer,它們可以儲(chǔ)存和操作字符串,即包含多個(gè)字符的字符數(shù)據(jù)。這個(gè)String類提供了數(shù)值不可改變的字符串。2013-04-04

