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

两种解决方案:

一、修改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
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值