springboot 使用ResponseEntity实现文件流下载

@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'

posted on 2022-04-11 22:38  路过君  阅读(430)  评论(0编辑  收藏  举报

导航