1、Controller
@ApiOperation(value = "IO流返回给前端")
@GetMapping("fileView")
public void fileView(@ApiParam(value = "文件路径", required = true) @RequestParam String fileUrl, HttpServletResponse response) {
fileService.fileView(fileUrl, response);
}
2、Service
/**
* 以IO流的形式返回给前端
*
* @param fileUrl 文件路径
* @param response resp
*/
public void fileView(String fileUrl, HttpServletResponse response) {
// 读取文件名 例:yyds.jpg
String fileName = fileUrl.substring(fileUrl.lastIndexOf("/") + 1);
try (FileInputStream inputStream = new FileInputStream(fileUrl);
OutputStream outputStream = response.getOutputStream()) {
byte[] data = new byte[1024];
// 全文件类型(传什么文件返回什么文件流)
response.setContentType("application/x-msdownload");
response.setHeader("Content-Disposition", "attachment; filename=\"" + fileName + "\"");
response.setHeader("Accept-Ranges", "bytes");
int read;
while ((read = inputStream.read(data)) != -1) {
outputStream.write(data, 0, read);
}
// 将缓存区数据进行输出
outputStream.flush();
} catch (IOException e) {
log.error("失败", e);
throw new Exception("exception");
}
}
3、另外一种写法
如果为小文件,则可直接写入,无须循环,效率更高
byte[] data = new byte[inputStream.available()];
inputStream.read(data);
response.set
......
outputStream.write(data);
这篇博客介绍了两种通过HTTP响应返回文件的方法。Controller层使用`@GetMapping`处理请求,Service层以IO流形式读取并返回文件。第一种方式采用循环读取并写入,适用于各种文件类型;第二种优化方案适用于小文件,直接读取并写入,提高效率。文章关注于后端如何高效地将文件以流形式传递给前端。
1367

被折叠的 条评论
为什么被折叠?



