springboot 返回文件流
在 Spring Boot 中返回文件流,可以使用 ResponseEntity 类。例如,你可以这样做:
@RestController
public class SpeechHandlerController {
@Autowired
private SpeechHandlerBiz speechHandlerBiz;
@PostMapping(value = {"/api/v1/ali/tts", "/openapi/v1/ali/tts"})
public ResponseEntity<InputStreamResource> textToSpeech(@RequestBody TtsRequest ttsRequest) throws FileNotFoundException {
File file = speechHandlerBiz.textToSpeech(ttsRequest);
InputStreamResource resource = new InputStreamResource(new FileInputStream(file));
return ResponseEntity.ok()
.header(HttpHeaders.CONTENT_DISPOSITION, "attachment;filename=" + file.getName())
.contentType(MediaType.APPLICATION_OCTET_STREAM)
.contentLength(file.length())
.body(resource);
}
}
这段代码会返回一个带有文件内容的响应,浏览器会将其作为文件下载。你也可以根据需要自定义响应头,例如设置文件名称、内容类型等
调用方接收流–使用Spring中的RestTemplate
方式一:postForEntity
RestTemplate restTemplate = new RestTemplate();
ResponseEntity<Resource> entity = restTemplate.postForEntity(url, paramObject, Resource.class);
InputStream in = entity.getBody().getInputStream();
方式二:exchange
// resource 接受流
ResponseEntity<Resource> responseEntity = restTemplate.exchange(url,
HttpMethod.POST, HttpEntity.EMPTY, Resource.class, new Object[0]);
// 直接根据resource获取流,进行文件操作
try(InputStream inputStream = responseEntity.getBody().getInputStream()) {
PDDocument load = PDDocument.load(inputStream);
PDFTextStripper pdfTextStripper = new PDFTextStripper();
String text = pdfTextStripper.getText(load);
} catch (IOException e) {
e.printStackTrace();
}