springboot 下载文件到当前项目目录下
时间: 2024-12-16 07:22:54 浏览: 28
Spring Boot 下载文件到当前项目目录通常涉及到HTTP响应,你可以使用Spring MVC的`ResponseEntity流`和`FileUtils.copyStreamToFile`等工具。以下是一个简单的示例:
```java
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.util.UriComponentsBuilder;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
@GetMapping("/download")
public ResponseEntity<InputStreamResource> downloadFile(@RequestParam("file") MultipartFile file) {
try {
// 检查文件是否上传成功
if (file.isEmpty()) {
return ResponseEntity.badRequest().build();
}
// 创建临时文件名
String tempFileName = UUID.randomUUID() + "_" + file.getOriginalFilename();
// 将请求体的内容保存到本地文件
File targetFile = new File(projectDirectoryPath, tempFileName);
FileOutputStream fos = new FileOutputStream(targetFile);
fos.write(file.getBytes());
fos.close();
// 创建输入流资源并设置Content-Disposition头信息
InputStream inputStream = new FileInputStream(targetFile);
HttpHeaders headers = new HttpHeaders();
headers.setContentDispositionFormData("filename", file.getOriginalFilename());
// 返回文件内容作为ResponseEntity
return ResponseEntity.ok()
.headers(headers)
.contentType(MediaType.APPLICATION_OCTET_STREAM)
.body(new InputStreamResource(inputStream));
} catch (IOException e) {
throw new RuntimeException("Failed to save or serve the file", e);
}
}
```
在这个例子中,`projectDirectoryPath`需要替换为你项目的实际目录路径。用户可以通过访问`/download?file=<file-name>`这样的URL下载指定的文件。
阅读全文
相关推荐


















