- 配置文件中配置靜態(tài)資源路徑和文件上傳大小限制
# 配置靜態(tài)資源的路徑swrs
spring.web.resources.static-locations=file:D:/files,classpath:static
# 限制單個文件的上傳大小ssmm
spring.servlet.multipart.max-file-size=100MB
# 限制多個文件的上傳大小ssmm
spring.servlet.multipart.max-request-size=500MB
-
定義負責(zé)處理文件上傳請求的Controller方法
controller.UploadController
package cn.tedu._03vehicle.controller; import cn.tedu._03vehicle.base.response.JsonResult; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import org.springframework.web.multipart.MultipartFile; import java.io.File; import java.io.IOException; import java.text.SimpleDateFormat; import java.util.Date; import java.util.UUID; @RestController @RequestMapping("/v1/file/") public class UploadController { /** * 1.上傳文件功能 * * @param file 前端提交的文件 * @return * @throws IOException */ @PostMapping("upload") public JsonResult upload(MultipartFile file) throws IOException { System.out.println("------------" + file); //最終目標(biāo): d:/files/2024/10/19/zhly.jpg /****************第1步:處理文件名****************/ //原始文件名字:zhly.jpg String fileName = file.getOriginalFilename(); //獲取文件的后綴名[.jpg] String suffix = fileName.substring(fileName.lastIndexOf(".")); //生成一個全球唯一的隨機字符串,作為新的文件名 fileName = UUID.randomUUID() + suffix; /**************第2步:處理路徑**************/ //目標(biāo): d:/files/2024/10/19/ String dirPath = "d:/files"; //自定義一個日期路徑作為文件存儲的文件夾,提高檢索性能,一般以年月日的格式存儲,比如:/2024/10/19 SimpleDateFormat sdf = new SimpleDateFormat("/yyyy/MM/dd/"); //將當(dāng)前的實際日期轉(zhuǎn)為上面的時間格式; String datePath = sdf.format(new Date()); /*************第3步:創(chuàng)建對應(yīng)的目錄**********/ File dirFile = new File(dirPath + datePath); if (!dirFile.exists()) { dirFile.mkdirs(); } /*************第4步:拼接文件完整路徑并保存到磁盤*********/ String filePath = dirPath + datePath + fileName; file.transferTo(new File(filePath)); /*************第5步:返回響應(yīng)*********************/ //返回: /2024/10/19/xxx.jpg 給到前端, 前端拼接成完整的文件路徑 //完整的文件路徑 http://localhost:8080/2024/10/19/xxx.jpg //此處沒有d:/files,因為后期會把該路徑設(shè)置為工程的靜態(tài)文件的根路徑 return JsonResult.ok(datePath + fileName); } }
-
注意事項
文件上傳成功后,假如希望可以通過瀏覽器直接訪問,需要配置靜態(tài)資源路徑
文件上傳現(xiàn)在是上傳到本地服務(wù)器對應(yīng)的地址,將來可以上傳到云端,例如阿里的OSS。
文件上傳的大小后續(xù)需要進行限制。