SpringBoot怎么实现文件存储和文件下载
时间: 2024-05-02 09:21:03 浏览: 215
SpringBoot可以通过以下方法实现文件存储和文件下载:
1. 文件存储
- 使用SpringBoot内置的文件上传组件MultipartFile来接收文件并保存到指定目录中。
示例代码:
```java
@PostMapping("/upload")
public String uploadFile(@RequestParam("file") MultipartFile file) {
try {
String fileName = StringUtils.cleanPath(file.getOriginalFilename());
Path path = Paths.get(uploadDir + fileName);
Files.copy(file.getInputStream(), path, StandardCopyOption.REPLACE_EXISTING);
return "File uploaded successfully!";
} catch (IOException e) {
throw new RuntimeException("Could not store the file. Error: " + e.getMessage());
}
}
```
- 使用第三方存储服务,如阿里云OSS、七牛云等。
示例代码:
```java
@Autowired
private OSSClient ossClient;
@PostMapping("/upload")
public String uploadFile(@RequestParam("file") MultipartFile file) {
try {
String fileName = StringUtils.cleanPath(file.getOriginalFilename());
InputStream inputStream = file.getInputStream();
ObjectMetadata objectMetadata = new ObjectMetadata();
objectMetadata.setContentLength(file.getSize());
ossClient.putObject(bucketName, fileName, inputStream, objectMetadata);
return "File uploaded successfully!";
} catch (IOException e) {
throw new RuntimeException("Could not store the file. Error: " + e.getMessage());
}
}
```
2. 文件下载
- 使用SpringBoot内置的响应实体类ResponseEntity,将文件以流的形式返回给客户端。
示例代码:
```java
@GetMapping("/download")
public ResponseEntity<Resource> downloadFile(@RequestParam("fileName") String fileName) {
try {
Path path = Paths.get(uploadDir + fileName);
Resource resource = new UrlResource(path.toUri());
return ResponseEntity.ok()
.contentType(MediaType.parseMediaType("application/octet-stream"))
.header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"" + resource.getFilename() + "\"")
.body(resource);
} catch (MalformedURLException e) {
throw new RuntimeException("Could not download the file. Error: " + e.getMessage());
}
}
```
- 使用第三方存储服务的下载接口,如阿里云OSS、七牛云等。
示例代码:
```java
@Autowired
private OSSClient ossClient;
@GetMapping("/download")
public void downloadFile(@RequestParam("fileName") String fileName, HttpServletResponse response) {
try {
OSSObject ossObject = ossClient.getObject(bucketName, fileName);
InputStream inputStream = ossObject.getObjectContent();
response.setContentType("application/octet-stream");
response.setHeader(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"" + fileName + "\"");
IOUtils.copy(inputStream, response.getOutputStream());
response.flushBuffer();
} catch (IOException e) {
throw new RuntimeException("Could not download the file. Error: " + e.getMessage());
}
}
```
阅读全文
相关推荐


















