前端 `` 選擇文件后,**瀏覽器出于安全考慮不會將客戶端絕對路徑傳給服務器**(現代瀏覽器僅傳文件名)。后端無法、也不應獲取客戶端本地路徑。
@PostMapping("/upload")
public String upload(@RequestParam("file") MultipartFile file) throws IOException {
if (file.isEmpty()) return "error";
String original = file.getOriginalFilename();
String ext = original.substring(original.lastIndexOf('.'));
String storedName = UUID.randomUUID() + ext;
Path dest = Paths.get(UPLOAD_ROOT, storedName);
Files.copy(file.getInputStream(), dest, StandardCopyOption.REPLACE_EXISTING);
// 存數據庫:originalName, storedName, size, contentType, uploadTime...
return "success";
}
@GetMapping("/download/{storedName}")
public void download(@PathVariable String storedName, HttpServletResponse resp) throws IOException {
Path file = Paths.get(UPLOAD_ROOT, storedName);
if (!Files.exists(file)) { resp.sendError(404); return; }
resp.setContentType(Files.probeContentType(file));
resp.setHeader("Content-Disposition", "attachment; filename=\"" + URLEncoder.encode(storedName, "UTF-8") + "\"");
Files.copy(file, resp.getOutputStream());
}
文件上傳的本質是**流傳輸 + 服務器落盤 + 元數據入庫**。忘掉客戶端路徑,擁抱流式處理。