在SpringBoot中上傳和下載文件可以通過以下步驟實現:
@RestController
public class FileUploadController {
@PostMapping("/upload")
public String uploadFile(@RequestParam("file") MultipartFile file) {
try {
// 保存文件到指定路徑
File newFile = new File("path/to/save/" + file.getOriginalFilename());
file.transferTo(newFile);
return "File uploaded successfully";
} catch (IOException e) {
return "File upload failed";
}
}
}
@RestController
public class FileDownloadController {
@GetMapping("/download/{fileName}")
public ResponseEntity<Resource> downloadFile(@PathVariable String fileName) {
Resource resource = new FileSystemResource("path/to/save/" + fileName);
HttpHeaders headers = new HttpHeaders();
headers.add(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=" + resource.getFilename());
return ResponseEntity.ok()
.headers(headers)
.contentLength(resource.contentLength())
.contentType(MediaType.APPLICATION_OCTET_STREAM)
.body(resource);
}
}
在上傳文件中,通過@RequestParam注解獲取上傳的文件,然后保存到指定路徑。在下載文件中,通過PathVariable注解獲取要下載文件的文件名,然后返回對應的文件資源,設置響應頭使瀏覽器下載文件。