下载文件时两种返回方式
设置文件响应header及contentType
public void downloadFloodInfo(HttpServletRequest request, HttpServletResponse response) {
String fileAllPath = "/xxxxxx/xxx/xxx.xxx";
File file = new File(fileAllPath);
if (file == null) {
try {
response.sendError(404, "文件不存在!");
return;
} catch (IOException e) {
e.printStackTrace();
}
}
try (
FileInputStream fileInputStream = new FileInputStream(new File(fileAllPath));
BufferedInputStream bufferedInputStream = new BufferedInputStream(fileInputStream);
ServletOutputStream outputStream = response.getOutputStream();
BufferedOutputStream bufferedOutputStream = new BufferedOutputStream(outputStream);
) {
// 设置response的Header
response.setCharacterEncoding("utf-8");
response.addHeader("Content-Disposition", "attachment;filename=" + FileUtils.setFileDownloadHeader(request, FILE_NAME));
response.addHeader("Content-Length", "" + FILE_SIZE);
response.setContentType("application/octet-stream");
byte[] buf = new byte[1024];
int length = 0;
while ((length = bufferedInputStream.read(buf)) != -1) {
bufferedOutputStream.write(buf, 0, buf.length);
}
} catch (Exception e) {
logger.info("读取文件{}异常 -> {}", FILE_NAME, e.getMessage());
}
}
直接返回文件
来源:https://blog.csdn.net/weixin_42548604/article/details/83827193
@RequestMapping("stream")
public void getStreamData(HttpServletResponse response) {
File file=new File("C:\\avi_vedio\\test.MP4");
ServletOutputStream out=null;
try {
FileInputStream instream=new FileInputStream(file);
byte[] b=new byte[1024];
int length=0;
BufferedInputStream buf=new BufferedInputStream(instream);
out=response.getOutputStream();
BufferedOutputStream bot=new BufferedOutputStream(out);
while((length=buf.read(b))!=-1) {
bot.write(b,0, b.length);
}
} catch (Exception e) {
// TODO Auto-generated catch block e.printStackTrace();
}
}

浙公网安备 33010602011771号