1. 通过FileInputStream读取文件输入流
public void export(String excelPath, String fileName) throws Exception{
//将文件存到指定位置
//读取目标文件流,转换调用下载
File resultFile = new File(excelPath);
FileInputStream resultFileFi = new FileInputStream(resultFile);
long l = resultFile.length();
int k = 0;
byte abyte0[] = new byte[65000];
// 调用下载
response.setContentType("application/x-msdownload");
response.setContentLength((int) l);
response.setHeader("Content-Disposition", "attachment; filename=" + fileName);
while ((long) k
int j;
j = resultFileFi.read(abyte0, 0, 65000);
k += j;
response.getOutputStream().write(abyte0, 0, j);
}
resultFileFi.close();
//转换成功后,删除临时文件
resultFile.delete();
}
2. 注意getServletContext().getMimeType(fileName),读取文件类型
public void export1(String excelPath, String fileName){
if (request.getParameter("file") != null) {
fileName = request.getParameter("file");
}
System.out.println(ServletActionContext.getServletContext().getMimeType(fileName));
response.setContentType(ServletActionContext.getServletContext().getMimeType(fileName));
response.setHeader("Content-disposition","attachment; filename="+fileName);
BufferedInputStream bis = null;
BufferedOutputStream bos = null;
try {
bis = new BufferedInputStream( new FileInputStream(excelPath) );
bos = new BufferedOutputStream(response.getOutputStream());
byte[] buff = new byte[2048];
int bytesRead;
while(-1 != (bytesRead = bis.read(buff, 0, buff.length))) {
bos.write(buff,0,bytesRead);
}
} catch(final IOException e) {
System.out.println ( "出现IOException." + e );
} finally {
if (bis != null)
try {
bis.close();
} catch (IOException e) {
e.printStackTrace();
}
if (bos != null)
try {
bos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}