这篇文章也是我收集的,如下:
碰到文件乱码,google了一下,发现
这篇文章还不赖
摘录如下:
之前,写过一个Download.jsp文件,可以解决下载文件乱码问题(诸如:DOC,XSL文件等等).
后来发现,遇到中文名的文件的时候,文件下载将会报错~~~~
今天,通过改写原Download.jsp文件已经彻底解决了这个问题~
现在,把一整套的文件上传下载的方法给贴出来~~~以便大家借鉴!~!~!~!~!
作者:古埃及法老
download.jsp文件
---------------------------------------------------------
1 <%
2 java.io.BufferedInputStream bis=null;
3 java.io.BufferedOutputStream bos=null;
4 try{
5 String filename=request.getParameter("filename");
6 filename=new String(filename.getBytes("iso8859-1"),"gb2312");
7 response.setContentType("application/x-msdownload");
8 response.setHeader("Content-disposition","attachment; filename="+new String(filename.getBytes("gb2312"),"iso8859-1"));
9 bis =new java.io.BufferedInputStream(new java.io.FileInputStream(config.getServletContext().getRealPath("files/" + filename)));
10 bos=new java.io.BufferedOutputStream(response.getOutputStream());
11 byte[] buff = new byte[2048];
12 int bytesRead;
13 while(-1 != (bytesRead = bis.read(buff, 0, buff.length))) {
14 bos.write(buff,0,bytesRead);
15 }
16 }
17 catch(Exception e){
18 e.printStackTrace();
19 }
20 finally {
21 if (bis != null)bis.close();
22 if (bos != null)bos.close();
23 }
24 %>
注意,关键就是
setHeader里的filename需要重新编码,格式是ISO-8859-1就OK了
以下是我自己项目中用到的代码片断,供参考:
list.jsp: 显示附件名称的页面
1 <tr>
2 <td height="25" class="tdcor">附 件 </td>
3 <td colspan="3" height=50>
4 <%
5 if (null != publish.getAttatchFilename() &&
6 publish.getAttatchFilename().length() > 0) {
7 %>
8 <a href="publish_do.jsp?method=download&fileName=
9 <%=URLEncoder.encode(publish.getAttatchFilename(),"GBK")%>">
10 <%=URLDecoder.decode(publish.getAttatchFilename(),"GBK")%></a>
11 <%
12 }
13 %>
14 </td>
15 </tr>
download.jsp:下载页面
1 else if (null != method && method.equals("download")) {//下载附件
2
3 String fileName = request.getParameter("fileName");
4 File file = new File(Constants.PUBLISH_FILE_PATH + "/" + URLDecoder.decode(fileName,"GBK"));
5 response.reset();
6 response.setContentType("application/octet-stream; charset=GBK");
7 response.addHeader("Content-Disposition", "attachment; filename=" + CourseDetailBusiness.transfer(URLDecoder.decode(fileName,"GBK"),"GBK","ISO-8859-1"));
8 response.setContentLength((int) file.length());
9
10 byte[] buffer = new byte[4096];
11 BufferedOutputStream output = null;
12 BufferedInputStream input = null;
13
14 // 写缓冲区:
15 try {
16 output = new BufferedOutputStream(response.getOutputStream());
17 input = new BufferedInputStream(new FileInputStream(file));
18
19 int n = (-1);
20 while ((n = input.read(buffer, 0, 4096)) > -1) {
21 output.write(buffer, 0, n);
22 }
23 response.flushBuffer();
24 }
25 catch (Exception e) {
26 } // maybe user cancelled download
27 finally {
28 if (input != null) input.close();
29 if (output != null) output.close();
30 }
说明:
1。文件名在数据库中保存的编码为URLEncode
2.在list.jsp显示的时候多了一次encode,不知为什么,不encode一次还不行,实际上是第二次编码了
posted on 2006-06-15 13:14
无声 阅读(3389)
评论(5) 编辑 收藏 所属分类:
职场生活