springboot用post返回文件流
时间: 2025-01-25 07:13:30 浏览: 36
在Spring Boot中,如果你需要通过POST请求返回一个文件作为响应,你可以利用`ResponseEntity`和`HttpHeaders`来实现。以下是一个简单的示例:
```java
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;
@PostMapping("/upload-file")
public ResponseEntity<StreamingResponseBody> downloadFile(@RequestParam("file") MultipartFile file) {
if (file.isEmpty()) {
return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(null);
}
try {
// 假设我们有一个处理文件的逻辑,这里仅做简单展示
byte[] bytes = file.getBytes();
// 创建一个响应体,用于流式传输
StreamingResponseBody outputStream = new StreamingResponseBody() {
@Override
public void write(OutputStream outputStream) throws IOException {
outputStream.write(bytes);
}
@Override
public void flush() throws IOException {
}
@Override
public void close() throws IOException {
}
};
// 设置Content-Disposition头信息,以便浏览器知道如何下载文件
HttpHeaders headers = new HttpHeaders();
headers.add(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"" + file.getOriginalFilename() + "\"");
// 返回文件流
return ResponseEntity.ok(outputStream)
.headers(headers)
.contentType(MediaType.APPLICATION_OCTET_STREAM);
} catch (Exception e) {
return ResponseEntity.badRequest().body(e.getMessage());
}
}
```
在这个例子中,当你向/upload-file发送一个包含文件的POST请求时,服务器会创建一个`StreamingResponseBody`来逐字节地写入文件内容,并设置适当的Content-Disposition头以指示它是一个可以下载的文件。
阅读全文
相关推荐


















