springboot文件上传下载示例代码
时间: 2023-04-01 18:04:11 浏览: 132
以下是 Spring Boot 文件上传下载的示例代码:
文件上传:
```java
@PostMapping("/upload")
public String uploadFile(@RequestParam("file") MultipartFile file) {
try {
// 获取文件名
String fileName = file.getOriginalFilename();
// 获取文件的字节数组
byte[] bytes = file.getBytes();
// 保存文件
Path path = Paths.get("uploads/" + fileName);
Files.write(path, bytes);
return "文件上传成功!";
} catch (IOException e) {
e.printStackTrace();
return "文件上传失败!";
}
}
```
文件下载:
```java
@GetMapping("/download")
public ResponseEntity<Resource> downloadFile(@RequestParam("fileName") String fileName) {
try {
// 加载文件资源
Path path = Paths.get("uploads/" + fileName);
Resource resource = new UrlResource(path.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();
}
}
```
阅读全文