给出springboot文件上传下载代码
时间: 2023-10-12 15:19:50 浏览: 78
Spring Boot 提供了很好的支持来处理文件上传和下载。下面是一个简单的示例代码:
1. 文件上传
```
@RestController
public class FileUploadController {
@Autowired
private StorageService storageService;
@PostMapping("/upload")
public ResponseEntity<String> handleFileUpload(@RequestParam("file") MultipartFile file) {
String message = "";
try {
storageService.store(file);
message = "You successfully uploaded " + file.getOriginalFilename() + "!";
return ResponseEntity.status(HttpStatus.OK).body(message);
} catch (Exception e) {
message = "FAIL to upload " + file.getOriginalFilename() + "!";
return ResponseEntity.status(HttpStatus.EXPECTATION_FAILED).body(message);
}
}
}
```
2. 文件下载
```
@RestController
public class FileDownloadController {
@Autowired
private StorageService storageService;
@GetMapping("/download/{fileName:.+}")
public ResponseEntity<Resource> downloadFile(@PathVariable String fileName, HttpServletRequest request) {
Resource resource = storageService.loadFileAsResource(fileName);
String contentType = null;
try {
contentType = request.getServletContext().getMimeType(resource.getFile().getAbsolutePath());
} catch (IOException ex) {
ex.printStackTrace();
}
if (contentType == null) {
contentType = "application/octet-stream";
}
return ResponseEntity.ok().contentType(MediaType.parseMediaType(contentType))
.header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"" + resource.getFilename() + "\"")
.body(resource);
}
}
```
其中,`StorageService` 是一个自定义的服务类,用于处理文件存储和加载。在这里不展开具体实现,可以自行搜索相关资料。
阅读全文