How to upload and download files in Spring Boot?
File upload and download in SpringBoot can be achieved by following these steps:
- Upload files:
@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";
}
}
}
- Download the files:
@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);
}
}
In file upload, use the @RequestParam annotation to retrieve the uploaded file and save it to a specified path. In file download, use the @PathVariable annotation to retrieve the file name to be downloaded, then return the corresponding file resource and set the response header to prompt the browser to download the file.