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);