java文件下载的文件名乱码
//
//下载文件,并处理文件名乱码
public void downloadFile(HttpServletRequest request,HttpServletResponse response){
String path = request.getSession().getServletContext().getRealPath("/upload/文档1.doc");
// path是根据日志路径和文件名拼接出来的
File file = new File(path);
//获取日志文件名称
String filename = file.getName();
try {
//判断是否是IE11
Boolean flag= request.getHeader("User-Agent").indexOf("like Gecko")>0;
//IE11 User-Agent字符串:Mozilla/5.0 (Windows NT 6.1; WOW64; Trident/7.0; rv:11.0) like Gecko
//IE6~IE10版本的User-Agent字符串:Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.0; Trident/6.0)
if (request.getHeader("User-Agent").toLowerCase().indexOf("msie") >0||flag){
filename = URLEncoder.encode(filename, "UTF-8");//IE浏览器
}else {
//先去掉文件名称中的空格,然后转换编码格式为utf-8,保证不出现乱码,
//这个文件名称用于浏览器的下载框中自动显示的文件名
filename = new String(filename.replaceAll(" ", "").getBytes("UTF-8"), "ISO8859-1");
//firefox浏览器
//firefox浏览器User-Agent字符串:
//Mozilla/5.0 (Windows NT 6.1; WOW64; rv:36.0) Gecko/20100101 Firefox/36.0
}
InputStream fis = new BufferedInputStream(new FileInputStream(path));
byte[] buffer;
buffer = new byte[fis.available()];
fis.read(buffer);
fis.close();
response.reset();
response.addHeader("Content-Disposition", "attachment;filename=" +filename);
response.addHeader("Content-Length", "" + file.length());
OutputStream os = response.getOutputStream();
response.setContentType("application/octet-stream");
os.write(buffer);// 输出文件
os.flush();
os.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}