如何在JSP文件中编写文件下载到响应

ame*_*lla 2 jsp download

当我尝试从响应对象获取ServletOutputStream对象时,我收到了java.lang.IllegalStateException.以下是我的代码:

<%@ page import="java.util.*,java.io.*"%>             

<%
try {
    System.out.print("request came");
    File f = new File ("E:/dd.txt");

    String name = f.getName().substring(f.getName().lastIndexOf("/") + 1,f.getName().length());
    InputStream in = new FileInputStream(f);

    ServletOutputStream outs = response.getOutputStream();

    response.setContentType ("application/txt");
    response.setHeader ("Content-Disposition", "attachment; filename="+f.getName()+"");
    int bit = 256;
    int i = 0;
    try {
        while ((bit) >= 0) {
            bit = in.read();
            outs.write(bit);
        }
    } catch (IOException ioe) {
        ioe.printStackTrace(System.out);
    }
    outs.flush();
    outs.close();
    in.close();         
} catch (Exception ioe) {
    ioe.printStackTrace(System.out);
}
%>
Run Code Online (Sandbox Code Playgroud)

以下是堆栈跟踪:

java.lang.IllegalStateException
   at org.apache.jasper.runtime.ServletResponseWrapperInclude.getOutputStream(ServletResponseWrapperInclude.java:63)
   at org.apache.jsp.html.portlet.vitage.custom.QUADWAVE.Procfiledownloadess1_005f36901_005f48.filedownload.downloadscreen_jsp._jspService(downloadscreen_jsp.java:5
   at org.apache.jasper.runtime.HttpJspBase.service(HttpJspBase.java:98)
   at javax.servlet.http.HttpServlet.service(HttpServlet.java:803)
   at org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:331)
   at org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:329)
   at org.apache.jasper.servlet.JspServlet.service(JspServlet.java:265)
   at javax.servlet.http.HttpServlet.service(HttpServlet.java:803)
Run Code Online (Sandbox Code Playgroud)

Bal*_*usC 5

您试图通过JSP文件中的某些代码下载文件.JSP作为一种视图技术实际上是工作的错误工具.外部的所有<% %>内容(通常是基于文本的内容,如HTML,XML,JSON等)也会写入HTTP响应,包括空格.这只会破坏由Java代码编写的下载内容的完整性,如果您正在提供文档/音频/视频文件等二进制文件,则更是如此.

因为JSP在内部使用您的具体问题是导致response.getWriter()打印所有模板内容(外面的一切<% %>),然后你尝试使用getOutputStream().这是一个非法的国家.您不能在单个响应中同时使用它们.除了使用之外getWriter(),您可以通过删除外部的任何空格来解决它<% %>,包括换行符.

所以,替换

<%@ page import="java.util.*,java.io.*"%>             

<%
    // Your Java code.
%>
Run Code Online (Sandbox Code Playgroud)

通过

<%@ page import="java.util.*,java.io.*"%><%
    // Your Java code.
%>
Run Code Online (Sandbox Code Playgroud)

(并且绝对确保在最后一个之后没有尾随空格/换行符%>)

但是,您实际上应该不使用JSP来完成工作.这就是说这个工作的错误工具.您应该为作业使用普通的HTTP Servlet类.只需创建一个扩展类,HttpServlet并将JSP中的所有Java代码移动到doGet()方法中.最后将该servlet映射到URL并调用该URL.

@WebServlet("/download")
public class DownloadServlet extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // Your Java code.
    }

}
Run Code Online (Sandbox Code Playgroud)

您可以在本文中找到更具体的示例.

也可以看看:


归档时间:

查看次数:

14271 次

最近记录:

7 年,5 月 前