springboot返回文件流
时间: 2023-03-31 19:03:46 浏览: 82
可以使用以下代码返回文件流:
```java
@GetMapping("/download")
public void downloadFile(HttpServletResponse response) throws IOException {
File file = new File("path/to/file");
response.setContentType("application/octet-stream");
response.setHeader("Content-Disposition", "attachment;filename=" + file.getName());
try (InputStream inputStream = new FileInputStream(file);
OutputStream outputStream = response.getOutputStream()) {
byte[] buffer = new byte[1024];
int len;
while ((len = inputStream.read(buffer)) != -1) {
outputStream.write(buffer, , len);
}
}
}
```
相关问题
Springboot如何接收文件流
在Spring Boot中,可以通过以下步骤接收文件流:
1. 在Controller中定义一个接收文件流的接口,例如:
```java
@PostMapping("/upload")
public String upload(@RequestParam("file") MultipartFile file) {
// 处理文件流
return "success";
}
```
其中,@RequestParam("file")用于获取上传的文件流,MultipartFile是Spring提供的一个用于表示上传文件的类。
2. 在接口中处理文件流,将其保存到本地,例如:
```java
String fileName = file.getOriginalFilename();
File dest = new File("path/to/" + fileName);
file.transferTo(dest);
```
其中,getOriginalFilename()方法用于获取上传文件的原始文件名,transferTo()方法用于将文件流保存到本地。
3. 返回处理结果。
需要注意的是,在前端需要通过multipart/form-data的方式将文件流上传到后端,例如:
```html
<form method="post" enctype="multipart/form-data" action="/upload">
<input type="file" name="file">
<button type="submit">上传</button>
</form>
```
以上是接收文件流的简单示例,具体实现需要根据具体的需求进行调整。
springboot下载文件
在Spring Boot中实现文件下载可以通过以下步骤来完成:
第一步:创建一个Controller类,用于处理文件下载的请求。在该类中,可以使用`@GetMapping`或`@RequestMapping`注解来指定处理的URL路径。然后,在对应的方法中,使用`ResponseEntity`来返回文件内容。例如,可以使用`FileInputStream`将文件读取为字节流,并将其包装在`ResponseEntity`中返回。
第二步:在前端页面中创建一个下载链接或按钮,通过点击该链接或按钮来触发文件下载的请求。可以使用`<a>`标签或`<button>`标签,并设置`href`属性或`onclick`事件来指定下载请求的URL。
下面是一个示例代码,演示了如何在Spring Boot中实现文件下载:
```java
@RestController
@RequestMapping("/common")
public class CommonController {
@GetMapping("/download")
public ResponseEntity<Resource> downloadFile() throws IOException {
// 读取文件内容
File file = new File("path/to/file");
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);
}
}
```
在前端页面中,可以使用以下代码来创建一个下载链接:
```html
<a href="/common/download">下载文件</a>
```
当用户点击该链接时,将会触发`/common/download`路径的请求,从而实现文件下载功能。
#### 引用[.reference_title]
- *1* *2* *3* [基于springboot文件上传和下载](https://blog.csdn.net/hyt_struggle/article/details/127168991)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v91^insertT0,239^v3^insert_chatgpt"}} ] [.reference_item]
[ .reference_list ]