在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注解获取要下载文件的文件名,然后返回对应的文件资源,设置响应头使浏览器下载文件。