因为项目需求要做一个导出的Excel的功能,但是用io直接做的话,文件会存在服务器上,用户拿不到,于是想了办法,现在服务器上创建一个,在把文件写进Response的io流中,这样就会在前台下载了,然后关流,删掉服务器上的文件。
private void loadExcel(File file,HttpServletResponse response) {
response.reset();
response.setHeader("Content-type", "application-download");
response.setContentType("application/x-excel");
response.setCharacterEncoding("UTF-8");
OutputStream out = null;
try {
response.setHeader("Content-Disposition", "attachment;filename=" + new String("cust.xls".getBytes("GB2312"), "ISO-8859-1"));
out = response.getOutputStream();
FileInputStream fileInputStream=new FileInputStream(file);
int d=-1;
while((d=fileInputStream.read())!=-1){
out.write(d);
}
// out.write(FileUtils.readFileToByteArray(file1));
fileInputStream.close();
out.write(FileUtils.readFileToByteArray(file));
out.flush();
out.close();
} catch (IOException e) {
e.printStackTrace();
}finally {
if (file.exists()) {
file.delete();
}
}
}