springboot 怎么实现文件服务器
时间: 2024-03-15 16:46:57 浏览: 14
在Spring Boot中实现文件服务器可以通过以下步骤:
1. 配置文件上传路径
在`application.properties`或`application.yml`中配置文件上传路径,例如:
```
spring.servlet.multipart.enabled=true
spring.servlet.multipart.file-size-threshold=2MB
spring.servlet.multipart.max-file-size=200MB
spring.servlet.multipart.max-request-size=215MB
upload.path=/data/file
```
其中`spring.servlet.multipart.*`是Spring Boot提供的文件上传配置,`upload.path`是自定义的文件上传路径。
2. 编写文件上传接口
编写文件上传接口,通过`@RequestParam`注解获取上传的文件,并使用`FileCopyUtils.copy()`方法将文件保存到指定路径下,例如:
```java
@RestController
public class FileUploadController {
@Value("${upload.path}")
private String uploadPath;
@PostMapping("/upload")
public String uploadFile(@RequestParam("file") MultipartFile file) throws IOException {
String fileName = file.getOriginalFilename();
File dest = new File(uploadPath + "/" + fileName);
FileCopyUtils.copy(file.getBytes(), dest);
return "upload success";
}
}
```
3. 编写文件下载接口
编写文件下载接口,通过`@PathVariable`注解获取文件名,然后使用`InputStreamResource`和`HttpHeaders`将文件返回给客户端,例如:
```java
@RestController
public class FileDownloadController {
@Value("${upload.path}")
private String uploadPath;
@GetMapping("/download/{fileName:.+}")
public ResponseEntity<InputStreamResource> downloadFile(@PathVariable String fileName) throws IOException {
File file = new File(uploadPath + "/" + fileName);
InputStreamResource resource = new InputStreamResource(new FileInputStream(file));
HttpHeaders headers = new HttpHeaders();
headers.add(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=" + file.getName());
return ResponseEntity.ok()
.headers(headers)
.contentLength(file.length())
.contentType(MediaType.APPLICATION_OCTET_STREAM)
.body(resource);
}
}
```
以上就是在Spring Boot中实现文件服务器的基本步骤,需要注意的是,建议在上传和下载接口中加上文件类型、大小等校验,以及权限验证等安全措施。