springboot文件上传下载代码
时间: 2023-04-03 21:01:07 浏览: 67
您好,以下是 Spring Boot 文件上传下载的示例代码:
文件上传:
```
@PostMapping("/upload")
public String uploadFile(@RequestParam("file") MultipartFile file) {
try {
// 获取文件名
String fileName = file.getOriginalFilename();
// 创建文件路径
Path filePath = Paths.get("uploads/" + fileName);
// 将文件保存到指定路径
Files.write(filePath, file.getBytes());
return "上传成功!";
} catch (IOException e) {
e.printStackTrace();
return "上传失败!";
}
}
```
文件下载:
```
@GetMapping("/download")
public ResponseEntity<Resource> downloadFile(@RequestParam("fileName") String fileName) {
try {
// 获取文件路径
Path filePath = Paths.get("uploads/" + fileName);
// 创建 Resource 对象
Resource resource = new UrlResource(filePath.toUri());
// 设置响应头
HttpHeaders headers = new HttpHeaders();
headers.add(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=" + fileName);
return ResponseEntity.ok()
.headers(headers)
.contentLength(resource.contentLength())
.contentType(MediaType.APPLICATION_OCTET_STREAM)
.body(resource);
} catch (MalformedURLException e) {
e.printStackTrace();
return ResponseEntity.notFound().build();
} catch (IOException e) {
e.printStackTrace();
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).build();
}
}
```
希望对您有所帮助!