文件名含中文的JavaWeb文件下载
2016-01-25 17:58
567 查看
在javaweb项目中实现文件下载,当文件名中包含中文文字时,需要进行如下的处理,才能在浏览器端正常显示中文文件名:
效果如下:
完整代码如下(只在Firefox上测试通过):
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); } } }
相关文章推荐
- 在eclipse 导入简单的Android studio 简单项目
- JAVA思考题,简单的数据加密和解密
- 最常见的eclipse快捷键
- 如何将Microstrategy For Mobile SDK项目从Eclipse转移到Android Studio中?
- javaweb学习总结(五)——Servlet学习1
- 【慕课笔记】U1 类和对象 第4节 JAVA中的成员变量和局部变量
- JAVA 深复制与浅复制
- java 引用类型
- Java 入门 之 面向对象 封装、继承与多态(一)
- java特种兵读书笔记(5-1)——并发之基础介绍
- Java读取excel文件写入txt
- Java 读取Excl文件 (poi-3.13)
- Java中的Enum的使用与分析
- spring boot简易入门
- The Java™ Tutorials —— Generics:前言
- Struts2设置默认的action
- Spring起步--helloworld
- 关于 Java 数组的 12 个最佳方法
- 【Eclipse】--Eclipse简介和安装
- 摘抄java基础