SSM项目 JSP页面中超链接含中文文件名,无法下载的问题解决

来源:互联网 发布:身份证录入软件 编辑:程序博客网 时间:2024/06/05 02:22

两种解决方案:

一、修改Tomcat配置文件 

在server.xml文件 ,找到如下代码

    <Connector port="8080" protocol="HTTP/1.1"                connectionTimeout="20000"                redirectPort="8443" />
在 />前加URIEncoding="UTF-8"即可

<Connector port="8080" protocol="HTTP/1.1"                  connectionTimeout="20000"                  redirectPort="8443"  URIEncoding="UTF-8"  />

但这样做有一个弊端,之前后台代码涉及到字符转换的都会出问题,

比如new String(fileName.getBytes("ISO-8859-1"),"utf-8");


二、后台代码通过字符流的形式处理

前台代码如下:

<a class="btn btn-small btn-success" href="manager/test/download.html?fileName=基本工资.xls" >基本工资表模板下载</a>

后台代码如下:

@RequestMapping(value = "/download")public void download(String fileName, HttpServletRequest request,HttpServletResponse response) throws IOException {response.setCharacterEncoding("utf-8");response.setContentType("application/vnd.ms-excel");response.setHeader("Content-Disposition", "attachment;fileName="+ fileName);// filename iso-8859-1格式String downloadName = new String(fileName.getBytes("ISO-8859-1"),"utf-8");// 转换为utf-8格式 file路径才可以找到InputStream inputStream = null;OutputStream outputStream = null;String path = request.getServletContext().getRealPath("file/app");byte[] bytes = new byte[2048];try {File file = new File(path, downloadName);inputStream = new FileInputStream(file);outputStream = response.getOutputStream();int length;// inputStream.read(bytes)从file中读取数据,-1是读取完的标志while ((length = inputStream.read(bytes)) > 0) {// 写数据outputStream.write(bytes, 0, length);}} catch (FileNotFoundException e) {e.printStackTrace();} catch (IOException e) {e.printStackTrace();} finally {// 关闭输入输出流if (outputStream != null) {outputStream.close();}if (inputStream != null) {inputStream.close();}}}

如果涉及到中文名的文件下载建议大家使用第二种,尽量不要去修改默认的服务器配置文件!


阅读全文
0 0