zl程序教程

您现在的位置是:首页 >  Javascript

当前栏目

springboot 使用ResponseEntity实现文件流下载

2023-04-18 13:08:15 时间
@GetMapping(value = "/api/file/{id}", produces = MediaType.APPLICATION_OCTET_STREAM_VALUE)
public ResponseEntity<StreamingResponseBody> download(
        @PathVariable(name = "id") String id
) {
	...
	return ResponseEntity.ok()
	    .header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=" + file.getName())
	    .contentType(MediaType.APPLICATION_OCTET_STREAM)
	    .body(outputStream -> {
	        try (InputStream inputStream = new FileInputStream(file)) {
	            StreamUtils.copy(inputStream, outputStream);
	        } catch (IOException e) {
	            
	        }
	    });
}

注:如果函数返回类型不写

ResponseEntity<StreamingResponseBody>

将报错

No converter for [class xxx$$Lambda$xxx] with preset Content-Type 'application/octet-stream'