在javaweb项目中实现文件下载,当文件名中包含中文文字时,需要进行如下的处理,才能在浏览器端正常显示中文文件名:
response.setContentType("octets/stream");
response.addHeader("Content-Type", "text/html; charset=utf-8");
response.addHeader("Content-Disposition", "attachment;filename="+new String(fileName.getBytes("UTF-8"),"ISO8859-1"));
效果如下:
完整代码如下(只在Firefox上测试通过):
public void download(HttpServletRequest request, HttpServletResponse response) {
try {
request.setCharacterEncoding("utf-8");
String path = request.getParameter("filePath");
if (StringUtils.isEmpty(path)) throw new Exception("文件位置错误");
path = URLDecoder.decode(path, "UTF-8");
File file=new File(path); String fileName=file.getName();
InputStream fis=new BufferedInputStream(new FileInputStream(path));
byte[] buffer=new byte[fis.available()]; fis.read(buffer);
fis.close();
response.reset();
response.setContentType("octets/stream");
response.addHeader("Content-Type", "text/html; charset=utf-8");
response.addHeader("Content-Disposition", "attachment;filename="+new String(fileName.getBytes("UTF-8"),"ISO8859-1"));
response.addHeader("Content-Length",""+ file.length());
OutputStream toClient=new BufferedOutputStream(response.getOutputStream());
response.setContentType("application/octet-stream");
toClient.write(buffer);
toClient.flush();
}
catch(Exception ex) {
logger.error(ex.getMessage(), ex);
response.setContentType("text/html;charset=UTF-8");
try {
response.getWriter().print("<script type='text/javascript'>alert('文件下载异常');</script>");
} catch (IOException e) {
logger.error(e.getMessage(), e);
}
}
}