Springboot 下载附件
@GetMapping("/download")
public void download(@RequestParam String fileId, HttpServletResponse response) throws IOException {
// 查询文件信息
SysFileEntity sysFileEntity = fileService.queryFileById(fileId);
response.setContentType("application/octet-stream");
response.addHeader("Content-Length", "" + sysFileEntity.getSize()); // 文件大小
response.addHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(sysFileEntity .getFileName(), "UTF-8"));
int bufferSize = 8 * 1024;
File file = new File(sysFileEntity.getFilePath());
# 指定 读、写缓冲区大小。不填时默认 缓冲区大小8192byte
BufferedInputStream bufferedInputStream = new BufferedInputStream(new FileInputStream(file), bufferSize);
BufferedOutputStream bufferedOutputStream = new BufferedOutputStream(response.getOutputStream(), bufferSize);
try {
// 设置缓冲区
byte[] bytes = new byte[bufferSize];
int len;
while ((len = bufferedInputStream.read(bytes, 0, bytes.length)) > 0){
bufferedOutputStream.write(bytes, 0, len);
}
bufferedOutputStream.flush();
}catch (Exception e){
logger.error("下载附件出错", e);
}finally {
IoUtil.close(bufferedOutputStream);
IoUtil.close(bufferedInputStream);
}
}
注意!!!!!!
response.setContentType("application/octet-stream");
response.addHeader("Content-Length", "" + sysFileEntity.getSize()); // 文件大小
response.addHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(sysFileEntity .getFileName(), "UTF-8"));
上述代码需写在response.getWriter或response.getOutputStream方法被调用之前。否则response.setContentType会不生效。
-
确保在调用response.setContentType方法之前,response.getWriter或response.getOutputStream方法没有被调用。因为一旦获取了响应的输出流或写入器,设置内容类型将不起作用。
-
确保在调用response.setContentType方法之前,没有向客户端发送任何数据。一旦开始向客户端发送数据,设置内容类型将不起作用。