目录
1、response的header中没有添加Content-Length导致下载的问价不完整
2、 从Spring Boot jar包下载/resources路径下的文件
1、response的header中没有添加Content-Length导致下载的问价不完整
/**
* @Description: 文件下载
* @MethodName: methodName
* @Param : filePath--文件全限定名
* @Return void
*/
public static void downloadFile(HttpServletResponse response, String filePath) {
String filename = filePath.substring(filePath.lastIndexOf('/') + 1);
File file = new File(filePath);
//判断文件父目录是否存在
if (file.exists()) {
//文件输入流
FileInputStream fis = null;
BufferedInputStream bis = null;
//输出流
OutputStream os = null;
//response.setContentType("application/force-download");
response.setContentType("application/x-msdownload");
response.setCharacterEncoding("UTF-8");
try {
response.setHeader("Content-Disposition", "attachment;fileName=" + URLEncoder.
encode(filename, "UTF-8"));
long fileLength = file.length();
//非常重要的一句话
response.setHeader("Content-Length", String.valueOf(fileLength));
byte[] buffer = new byte[2048];
os = response.getOutputStream();
fis = new FileInputStream(file);
bis = new BufferedInputStream(fis);
int i = bis.read(buffer);
while (i != -1) {
os.write(buffer);
i = bis.read(buffer);
}
} catch (Exception e) {
log.error("error: {}", e.getMessage());
e.printStackTrace();
} finally {
try {
if (null != bis) {
bis.close();
}
if (null != fis) {
fis.close();
}
if (null != os) {
os.close();
}
} catch (IOException e) {
log.error("error: {}", e.getMessage());
e.printStackTrace();
}
}
} else {
try {
response.sendError(404, "File not found!");
} catch (Exception e) {
e.printStackTrace();
}
}
}
非常重要的一句话
response.setHeader("Content-Length", String.valueOf(fileLength));
因为没有写他,导致下载的word文档在wins用office打开时候 报错(文档最后生成多余的标签)
2、 从Spring Boot jar包下载/resources路径下的文件
要用当前类去获取resources的路径,才能去拿到根路径
this.getClass().getResourceAsStream("/import/hire_info_template.xlsx");
@RequestMapping("/download")
public void downloadFile(HttpServletResponse response) {
try {
InputStream inputStream = this.getClass().getResourceAsStream("/import/hire_info_template.xlsx");
//强制下载不打开
response.setContentType("application/force-download");
OutputStream out = response.getOutputStream();
//使用URLEncoder来防止文件名乱码或者读取错误
response.setHeader("Content-Disposition", "attachment; filename=" + URLEncoder.encode("hire_info_template.xlsx", "UTF-8"));
int b = 0;
byte[] buffer = new byte[1000000];
while (b != -1) {
b = inputStream.read(buffer);
if (b != -1) out.write(buffer, 0, b);
}
inputStream.close();
out.close();
out.flush();
} catch (IOException e) {
e.printStackTrace();
}
}