SpringBoot中怎么上传和下载文件
在SpringBoot中上传和下载文件可以通过以下步骤实现:
- 上传文件:
@RestControllerpublic 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";}}}
- 下载文件:
@RestControllerpublic 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注解获取要下载文件的文件名,然后返回对应的文件资源,设置响应头使浏览器下载文件。
上一篇:MyBatis扩展插件怎么使用
下一篇:php怎么输出菱形图案
SpringBoot
webacc.exe是什么文件?webacc.exe是不是病毒
WINSYS.vbs是什么文件?WINSYS.vbs是不是病毒
winssh.exe是什么文件?winssh.exe是不是病毒
wt.exe是什么文件?wt.exe是不是病毒
winsysetm.exe是什么文件?winsysetm.exe是不是病毒
winstrve.exe是什么文件?winstrve.exe是不是病毒
winsysupd7.exe是什么文件?winsysupd7.exe是不是病毒
winsysupd.exe是什么文件?winsysupd.exe是不是病毒
winsysupd2.exe是什么文件?winsysupd2.exe是不是病毒
winsysupd8.exe是什么文件?winsysupd8.exe是不是病毒