SpringBoot文件上傳功能的實(shí)現(xiàn)方法
1.應(yīng)用實(shí)例
需求: 演示 Spring-Boot 通過表單注冊用戶,并支持上傳圖片
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>注冊用戶~</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="注冊"/> <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ā)到用戶注冊-可以完成文件上傳頁面 @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 "注冊用戶成功/文件上傳成功"; } }
3.引出兩個(gè)問題
1.文件覆蓋問題
上面的示例中實(shí)現(xiàn)了文件的上傳,但當(dāng)兩個(gè)不同的文件文件名相同時(shí)會(huì)存在文件覆蓋的問題,如何解決呢?
@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 "注冊用戶成功/文件上傳成功"; }
originalFilename = UUID.randomUUID().toString().replaceAll("-","")+System.nanoTime()+originalFilename;
,實(shí)現(xiàn)思路就是給上傳的文件重新指定一個(gè)不重復(fù)的文件名
2.將文件都上傳到一個(gè)目錄下,當(dāng)上傳文件很多時(shí),會(huì)造成訪問文件速度變慢
解決思路:將文件上傳到不同目錄 比如 一天上傳的文件,統(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 "注冊用戶成功/文件上傳成功"; }
到此這篇關(guān)于SpringBoot文件上傳功能的實(shí)現(xiàn)方法的文章就介紹到這了,更多相關(guān)SpringBoot文件上傳內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
@NotEmpty、@NotBlank、@NotNull的區(qū)別
這篇文章主要介紹了@NotEmpty、@NotBlank、@NotNull的區(qū)別,需要的朋友可以參考下2016-09-09Java Spring Controller 獲取請求參數(shù)的幾種方法詳解
這篇文章主要介紹了Java Spring Controller 獲取請求參數(shù)的幾種方法詳解的相關(guān)資料,這里提供了6種方法,需要的朋友可以參考下2016-12-12java短信驗(yàn)證碼獲取次數(shù)限制實(shí)例
這篇文章主要介紹了java短信驗(yàn)證碼獲取次數(shù)限制實(shí)例,小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過來看看吧2018-01-01Java 數(shù)據(jù)結(jié)構(gòu)與算法系列精講之二叉堆
二叉堆是一種特殊的堆,其實(shí)質(zhì)是完全二叉樹。二叉堆有兩種:最大堆和最小堆。最大堆是指父節(jié)點(diǎn)鍵值總是大于或等于任何一個(gè)子節(jié)點(diǎn)的鍵值。而最小堆恰恰相反,指的是父節(jié)點(diǎn)鍵值總是小于任何一個(gè)子節(jié)點(diǎn)的鍵值2022-02-02