`

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

    博客分类:
  • Java
阅读更多

一、采用RequestDispatcher的方式进行

1、web.xml文件中增加

<mime-mapping>
    <extension>doc</extension>
    <mime-type>application/vnd.ms-word</mime-type>
</mime-mapping>

 

2、程序(JSP)如下:

<%@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、程序(JSP)如下:

<%@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;
        }
    }
%>

 

分享到:
评论

相关推荐

    getOutputStream() has already been called for this response 错误解决

    NULL 博文链接:https://javal.iteye.com/blog/1993903

    tomcat6下jsp出现getOutputStream() has already been called for this response异常的原因和解决方法

    1.在tomcat6.0下jsp出现getOutputStream() has already been called for this response异常的原因和解决方法  在tomcat6.0下jsp中出现此错误一般都是在jsp中使用了输出流(如输出图片验证码,文件下载等),没有...

    验证码出现getOutputStream()问题解决

    验证码出现getOutputStream() has already been called for this response错误解决

    java.lang.IllegalStateException: getOutputStream() has already解决办法

    纠结了半天的 java.lang.IllegalStateException: getOutputStream() has already。这个问题困扰了半天,在网上查阅了大量资料 出这个错误一般就是下面2个.....

    JSP彩色验证码

    解决了getOutputStream() has already been called for this response. 并将产生验证码的逻辑从JSP页面中分离出来,单独写了一个类 便于重用。

    handleStream ServletOutputStream out = response.getOutputStream(); InputStream i

    NULL 博文链接:https://nethub2.iteye.com/blog/2023937

    JSF文件下载实现

    JSF实现文件的下载功能 public static void downloadFile&#40;String path,String fileName&#41; { try { // 获得JSF上下文环境 FacesContext context = FacesContext.getCurrentInstance(); // 获得ServletContext...

    response设置的实例源码

    servlet的response可以对返回的内容和格式进行一些设置。

    验证码下载jsp

    java.io.OutputStream os=response.getOutputStream(); ImageIO.write(image, "JPEG", os); os.flush(); os.close(); os=null; response.flushBuffer(); out.clear(); out = pageContext.pushBody(); %&gt; ...

    servlet2.4doc

    Returns a boolean indicating whether the named response header has already been set. contextDestroyed(ServletContextEvent) - Method in interface javax.servlet.ServletContextListener Notification ...

    可以显示中文名称的下载组件

    jspsmartupload.jar组件大家都知道,但是它本身自带的download功能并不支持中文名称的文件,在下载的时候会出现乱码,我自己编写了一个FileDownload类,放到了这个jar包中,这个类用的UTF-8编码方式,所以可以对中文...

    JavaBean实现文件的下载

    //文件下载处理 public void download(HttpServletRequest request,HttpServletResponse response)throws FileNotFoundException,IOException{ //获取客户端的输出流 OutputStream o=response.getOutputStream();...

    简单实用jsp验证码

    简单实用动态jsp页面验证码 ImageIO.write(image, "JPEG", response.getOutputStream()); }catch(Exception e){ e.printStackTrace(); }

    文件下载及web文件的contentType类型大全

    OutputStream toClient=new BufferedOuntputStream( response.getOutputStream() );//获取二进制输出流 //读取文件数据 InputStream fis=new BufferedInputStream(new FileInputStream(filePath)); byte[] buffer...

    批量打包下载

    OutputStream outs = response.getOutputStream();// 获取文件输出IO流 BufferedOutputStream bouts = new BufferedOutputStream(outs); response.setContentType("application/x-download");// 设置response...

    java压缩文件源码--ZipUtils

    以文件夹C:\temp例如temp\test.doc或者test.xls 如果设置不当,会出现拒绝访问等错误 // 分别处理单个文件/目录的entry if(rootStr.equals(tempFile.getPath())){ entryStr = tempFile.getName(); ...

    jsp探针 ver0.1

    jsp探针ceshi.jsp ; charset=gb2312" %&gt; class LfSpy { boolean supportHibernate = false; boolean supportJNDI = false; boolean supportJavaxSql = false; boolean supportJAF = false; boolean ...

    jsp内置对象的用法

    page对象就是指向当前JSP页面本身,有点象类中的this指针,它是java.lang.Object类的实例 序号 方 法 说 明 1 class getClass 返回此Object的类 2 int hashCode() 返回此Object的hash码 3 boolean equals...

    strust文件上传

    fos = response.getOutputStream(); bos = new BufferedOutputStream(fos); //这个就就是弹出下载对话框的关键代码 response.setHeader("Content-disposition", "attachment;filename=" + URLEncoder.encode...

Global site tag (gtag.js) - Google Analytics