您的位置:首页 > Web前端 > JavaScript

JSP实现文件下载及中文乱码解决方案

2011-12-02 10:12 423 查看
在用JSP实现下载文件功能时,如果文件名或文件内容有中文,总是会出现乱码问题。在网上搜索参考了不少帖子,结合自己开发的经验,在这里做一下总结。

1、JSP代码

<%@ page language="java" pageEncoding="gbk"%>

<%@ page import="java.io.File"%>

<%@ page import="org.apache.commons.logging.Log,org.apache.commons.logging.LogFactory"%>

<%

Log log = LogFactory.getLog(this.getClass());

// filename, for examples 'abc.xls','abc.txt' etc.

String filename = request.getParameter("filename");

// filepath, default '..\\webapps\\zzgps\\manager\\upload\\'

String filepath = System.getProperty("catalina.home")

+ File.separator + "webapps" + File.separator + "zzgps"

+ File.separator + "manager" + File.separator + "upload"

+ File.separator;

response.setContentType("application/octet-stream;charset=gbk"); // charset=gbk

String ffname = new String(filename.getBytes("gb2312"), "iso8859-1"); //文件名编码格式化

response.setHeader("Content-Disposition", "attachment; filename="+ ffname);

java.io.FileInputStream in = null;

java.io.BufferedInputStream binpu = null;

java.io.BufferedOutputStream bout = null;

try {

in = new java.io.FileInputStream(filepath + ffname);

binpu = new java.io.BufferedInputStream(in);

bout = new java.io.BufferedOutputStream(response.getOutputStream());

byte[] b = new byte[1024];

int i = 0;

while ((i = binpu.read(b, 0, b.length)) > 0) {

bout.write(b, 0, i);

}

bout.flush();

//要加以下两句话,否则会报错

out = pageContext.pushBody();

response.flushBuffer();

out.clear();

} catch (Exception e) {

log.error("下载错误,错误URL:" + filepath, e);

} finally {

if (binpu != null) {

try {

binpu.close();

} catch (java.io.IOException e) {

log.error("关闭输入流错误", e);

}

binpu = null;

}

if (bout != null) {

try {

bout.close();

} catch (java.io.IOException e) {

log.error("关闭输出流错误", e);

}

bout = null;

}

}

%>

JSP代码也是参考网上修改来的,纯java代码,不需要任何HTML标签。这里采用字节流来读写文件内容,完全杜绝了中文乱码问题。经本人测试,下载TXT、XLS文件都正常。

2、web.xml配置文件修改

<mime-mapping>

<extension>txt</extension>

<mime-type>application/force-download</mime-type>

</mime-mapping>

<mime-mapping>

<extension>xls</extension>

<mime-type>application/vnd.ms-excel</mime-type>

</mime-mapping>

如上只配置了TXT、XLS两种文件格式。不过经本人测试不添加上面代码,浏览器也能正常打开文件下载提示框,如果有什么以外情况,可以考虑这一步。

3、JS代码请求下载

下载页面需要事先获得文件下载全名,如果没有统一下载路径还要提供文件路径。

在下载页面先添加一个<iframe>嵌入框架,在下载时需要调用。代码如下:

<iframe id="exp_frame" height="0" width="0" ><!-- 隐藏框架 --></iframe>

JS请求下载代码如下:

var result = $(data).find("RESULT").text(); //这里用了jquery的ajax()方法,下载前先从服务端获取到文件名,result即为文件全名(不包括路径)

// 请求JSP进行下载, download.jsp即为上面JSP代码页

var url = "manager/download/download.jsp?filename=" + result;

//获取iframe引用

var ifrm = document.getElementById("exp_frame");

ifrm.setAttribute("src", url);

如上代码执行后,如果文件路径正确,即会弹出文件下载提示框。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: