将文件名重新用“ISO8859_1”编码
2、下载自定义文件名:
Response 设置头文件类型 “Content-disposition”,值为“ attachment;filename="文件名" ”
3、获取文件的MIME类型
通过 ServletContext 的 getMimeType(String filename),即通过文件的后缀名得到注册在tomcat中的相应MIME类型
4、实例(要下载的文件在WebRoot/file/模版文件.xls):
@Override
public void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
req.setCharacterEncoding("UTF-8");
String referPath = req.getHeader("Refer");
String fileName = req.getSession()
.getServletContext()
.getRealPath("/")+"file/temp.xls";
File file = new File(fileName);
if (file == null || !file.exists() ) {
System.out.println("文件不存在 : "+fileName);
resp.sendRedirect(referPath);
}
resp.setCharacterEncoding("UTF-8");
String fileType = req.getSession()
.getServletContext()
.getMimeType(fileName);
if (fileType==null) {
fileType = "application/octet-stream";
}
resp.setContentType(fileType);
System.out.println("文件类型是:"+fileType);
String newFileName = new String("模版文件.xls".getBytes(), "ISO8859_1");
resp.setHeader("Content-disposition", "attachment;filename=\""+newFileName+"\"");
BufferedInputStream bis = new BufferedInputStream(new FileInputStream(file));
BufferedOutputStream bos = new BufferedOutputStream(resp.getOutputStream());
byte[] buffer = new byte[1024];
int length = 0;
while((length = bis.read(buffer)) != -1){
bos.write(buffer, 0, length);
}
if (bis != null) bis.close();
if (bos != null) bos.close();
}