首页 > java > 文件下载(解决中文文件名下载乱码问题)

文件下载(解决中文文件名下载乱码问题)

2008年12月28日 发表评论 阅读评论

下面的代码可解决此问题:
java 代码

<%@ page contentType="text/html;charset=utf-8" %>
<%@ page import = "java.util.*" %>
<%@ page import = "java.io.*" %>
<%@ page import = "java.net.*" %>
<% //防止IE缓存 response.setHeader("pragma","no-cache"); response.setHeader("cache-control","no-cache"); response.setDateHeader("Expires",0); //设置编码 request.setCharacterEncoding("UTF-8"); String fileName = request.getParameter("fileName"); //取到文件 File file = new File(application.getRealPath("/")+"upload/" + fileName); response.reset(); //response.setContentType("application/octet-stream;charset=UTF-8"); response.setContentType("application/octet-stream;charset=GBK");//解决在弹出文件下载框不能打开文件的问题 //System.out.println(response.getCharacterEncoding()); //一定要对fileName进行encode //response.addHeader("Content-Disposition", "attachment; filename=" + java.net.URLEncoder.encode(fileName, "UTF-8")); response.addHeader("Content-Disposition", "attachment; filename=" + new String(fileName.getBytes("GBK"),"ISO8859-1"));//解决在弹出文件下载框不能打开文件的问题 response.setContentLength((int) file.length()); byte[] buffer = new byte[4096]; BufferedOutputStream output = null; BufferedInputStream input = null; // 写缓冲区: try { output = new BufferedOutputStream(response.getOutputStream()); input = new BufferedInputStream(new FileInputStream(file)); int n = (-1); while ((n = input.read(buffer, 0, 4096)) > -1) {
output.write(buffer, 0, n);
}
response.flushBuffer();
}
catch (Exception e) {
} // maybe user cancelled download
finally {
if (input != null) input.close();
if (output != null) output.close();
}
%>

分类: java 标签: 3,249 次阅读
原文链接:http://www.wenhq.com/article/view_229.html
欢迎转载,请注明出处:亲亲宝宝
  1. 本文目前尚无任何评论.
  1. 本文目前尚无任何 trackbacks 和 pingbacks.