jsp实现文件下载与中文文件名乱码问题解决

【转】jsp实现文件下载与中文文件名乱码问题解决(3)

JSP文件下载及出现getOutputStream() has already been called for this response的解决方法

http://iamin.blogdriver.com/iamin/1072546.html

一、采用RequestDispatcher的方式进行

1、web.xml文件中增加
<mime-mapping>
    <extension>doc</extension>
    <mime-type>application/vnd.ms-word</mime-type>
</mime-mapping>


2、程序如下:

<%@page language="java" import="java.net.*" pageEncoding="gb2312"%>
<%
    response.setContentType("application/x-download");//设置为下载application/x-download
    String filenamedownload = "/系统解决方案.doc";//即将下载的文件的相对路径
    String filenamedisplay = "系统解决方案.doc";//下载文件时显示的文件保存名称
    filenamedisplay = URLEncoder.encode(filenamedisplay,"UTF-8");
    response.addHeader("Content-Disposition","attachment;filename=" + filenamedisplay);
   
    try
    {
        RequestDispatcher dispatcher = application.getRequestDispatcher(filenamedownload);
        if(dispatcher != null)
        {
            dispatcher.forward(request,response);
        }
        response.flushBuffer();
    }
    catch(Exception e)
    {
        e.printStackTrace();
    }
    finally
    {
   
    }
%>


二、采用文件流输出的方式下载

1、web.xml文件中增加
<mime-mapping>
    <extension>doc</extension>
    <mime-type>application/vnd.ms-word</mime-type>
</mime-mapping>


2、程序如下:

<%@page language="java" contentType="application/x-msdownload" import="java.io.*,java.net.*" pageEncoding="gb2312"%><%
    //关于文件下载时采用文件流输出的方式处理:
    //加上response.reset(),并且所有的%>后面不要换行,包括最后一个;
    //因为Application Server在处理编译jsp时对于%>和<%之间的内容一般是原样输出,而且默认是PrintWriter,
    //而你却要进行流输出:ServletOutputStream,这样做相当于试图在Servlet中使用两种输出机制,
    //就会发生:getOutputStream() has already been called for this response的错误
    //详细请见《More Java Pitfill》一书的第二部分 Web层Item 33:试图在Servlet中使用两种输出机制 270
    //而且如果有换行,对于文本文件没有什么问题,但是对于其它格式,比如AutoCAD、Word、Excel等文件
    //下载下来的文件中就会多出一些换行符0x0d和0x0a,这样可能导致某些格式的文件无法打开,有些也可以正常打开。

    response.reset();//可以加也可以不加
    response.setContentType("application/x-download");//设置为下载application/x-download
    // /../../退WEB-INF/classes两级到应用的根目录下去,注意Tomcat与WebLogic下面这一句得到的路径不同,WebLogic中路径最后没有/
    System.out.println(this.getClass().getClassLoader().getResource("/").getPath());
    String filenamedownload = this.getClass().getClassLoader().getResource("/").getPath() + "/../../系统解决方案.doc";
    String filenamedisplay = "系统解决方案.doc";//系统解决方案.txt
    filenamedisplay = URLEncoder.encode(filenamedisplay,"UTF-8");
    response.addHeader("Content-Disposition","attachment;filename=" + filenamedisplay);

    OutputStream output = null;
    FileInputStream fis = null;
    try
    {
        output = response.getOutputStream();
        fis = new FileInputStream(filenamedownload);

        byte[] b = new byte[1024];
        int i = 0;

        while((i = fis.read(b)) > 0)
        {
            output.write(b, 0, i);
        }
        output.flush();
    }
    catch(Exception e)
    {
        System.out.println("Error!");
        e.printStackTrace();
    }
    finally
    {
        if(fis != null)
        {
            fis.close();
            fis = null;
        }
        if(output != null)
        {
            output.close();
            output = null;
        }
    }
%>

之前,写过一个Download.jsp文件,可以解决下载文件乱码问题(诸如:DOC,XSL文件等等).
后来发现,遇到中文名的文件的时候,文件下载将会报错~~~~
今天,通过改写原Download.jsp文件已经彻底解决了这个问题~
现在,把一整套的文件上传下载的方法给贴出来~~~以便大家借鉴!~!~!~!~!
作者:古埃及法老

download.jsp文件
---------------------------------------------------------

<%
   java.io.BufferedInputStream bis=null;
   java.io.BufferedOutputStream   bos=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("files/" + filename)));
bos=new java.io.BufferedOutputStream(response.getOutputStream());
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();
}
%>



注意,关键就是setHeader里的filename需要重新编码,格式是ISO-8859-1就OK了

以下是我自己项目中用到的代码片断,供参考:

list.jsp: 显示附件名称的页面

<tr>
            <td height="25" class="tdcor">附&nbsp;&nbsp;件&nbsp;</td>
            <td colspan="3" height=50>
                <%
                    if (null != publish.getAttatchFilename() &&
publish.getAttatchFilename().length() > 0) {
                %>
                <a href="publish_do.jsp?method=download&fileName=
<%=URLEncoder.encode(publish.getAttatchFilename(),"GBK")%>">
<%=URLDecoder.decode(publish.getAttatchFilename(),"GBK")%></a>
                <%
                     }
                %>
            </td>
</tr>


download.jsp:下载页面

else if (null != method && method.equals("download")) {//下载附件

         String fileName = request.getParameter("fileName");
         File file = new File(Constants.PUBLISH_FILE_PATH + "/" + URLDecoder.decode(fileName,"GBK"));
         response.reset();
         response.setContentType("application/octet-stream; charset=GBK");
         response.addHeader("Content-Disposition", "attachment; filename=" + CourseDetailBusiness.transfer(URLDecoder.decode(fileName,"GBK"),"GBK","ISO-8859-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();
         }



说明:
1。文件名在数据库中保存的编码为URLEncode
2.在list.jsp显示的时候多了一次encode,不知为什么,不encode一次还不行,实际上是第二次编码了

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值