普偏JSP代有中文的文件下载会出现乱码现象,最近整理网上的例子,解决发放如下
下载连接页
<% String fname ="文件.rar%>
<% String tf=new String (fname.getBytes("utf-8"),"GBK");%>
<a target="_blank" href="download.jsp?filename=<%=URLEncoder.encode(fname,"GBK")%>">下载</a>
下载页面:
<%
out.clear();
out = pageContext.pushBody();
java.io.BufferedInputStream bis = null;
java.io.BufferedOutputStream bos = null;
OutputStream os = null;
try {
String filename = request.getParameter("filename");
filename = new String(filename.getBytes("iso8859-1"), "gb2312");
response.setContentType("application/x-msdownload");
response.setHeader("Content-disposition",
"attachment; filename="
+ new String(filename.getBytes("gb2312"),
"iso8859-1"));
bis = new java.io.BufferedInputStream(
new java.io.FileInputStream(config.getServletContext()
.getRealPath(filename)));
os = response.getOutputStream();
bos = new java.io.BufferedOutputStream(os);
byte[] buff = new byte[2048];
int bytesRead;
while (-1 != (bytesRead = bis.read(buff, 0, buff.length))) {
bos.write(buff, 0, bytesRead);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
if (bis != null)
bis.close();
if (bos != null)
bos.close();
if (os != null)
os.close();
}
%>
这段代码解决了下载报错的问题,必须添加上去
out.clear();
out = pageContext.pushBody();