excel转为流,进行下载。本地可以,服务器报:
java.io.FileNotFoundException: file:\E:\liziyi\guopei6\gp6-exam\target\gp6-exam-0.0.1-SNAPSHOT.jar!\BOOT-INF\classes!\exceltemplate\exam_record_import_template.xls (文件名、目录名或卷标语法不正确。)
因为服务器上是要打jar包,运行的。这时候再查询文件地址,会报错
public String download(String fileName, String folder, HttpServletRequest request, HttpServletResponse response) {
response.setCharacterEncoding("utf-8");
response.setContentType("multipart/form-data");
response.setHeader("Content-Disposition", "attachment;fileName=" + fileName);
try {
String path = this.getClass().getClassLoader().getResource(folder + "/" + fileName).getPath();
InputStream inputStream = new FileInputStream(new File(path));
OutputStream os = response.getOutputStream();
byte[] b = new byte[2048];
int length;
while ((length = inputStream.read(b)) > 0) {
os.write(b, 0, length);
}
// 这里主要关闭。
os.close();
inputStream.close();
} catch (IOException e) {
log.error(e.getMessage(), e);
}
return null;
}
因为jar属于压缩包,所以要使用getResourceAsStream,不能使用getResource
public String download(String fileName, String folder, HttpServletRequest request, HttpServletResponse response) {
response.setCharacterEncoding("utf-8");
response.setContentType("multipart/form-data");
response.setHeader("Content-Disposition", "attachment;fileName=" + fileName);
try {
InputStream inputStream = this.getClass().getClassLoader().getResourceAsStream(folder + "/" + fileName);
OutputStream os = response.getOutputStream();
byte[] b = new byte[2048];
int length;
while ((length = inputStream.read(b)) > 0) {
os.write(b, 0, length);
}
// 这里主要关闭。
os.close();
inputStream.close();
} catch (FileNotFoundException e) {
log.error(e.getMessage(), e);
} catch (IOException e) {
log.error(e.getMessage(), e);
}
return null;
}
待补充:
excel,先生成,再下载
excel使用多线程和redis下载文件
|