Java下载文件(流的形式)

时间:2023-03-09 02:56:46
Java下载文件(流的形式)
     @RequestMapping("download")
@ResponseBody
public void download(HttpServletResponse response, Integer userId, String fileUrl) {
try {
File file=new File(fileUrl);
String filename=file.getName();
// 以流的形式下载文件。
InputStream fis = new BufferedInputStream(new FileInputStream(fileUrl));
byte[] buffer = new byte[fis.available()];
fis.read(buffer);
fis.close();
// 清空response
response.reset(); response.setContentType("application/octet-stream;charset=UTF-8");
String fileName = new String(filename.getBytes("gb2312"), "iso8859-1");
response.setHeader("Content-disposition", "attachment;filename=" + fileName);
OutputStream ouputStream = response.getOutputStream();
ouputStream.write(buffer);
ouputStream.flush();
ouputStream.close();
} catch (Exception e) {
e.printStackTrace();
logger.error("文件下载出现异常", e);
}
}