How to serve a file with JSP?

萝らか妹 提交于 2019-12-01 16:58:58

To the point, just write the same code in JSP as you would do in a Servlet class. You can practically copypaste it. Only ensure that you are not writinig any template text to the stream, this includes linebreaks and whitespace outside the scriptlets. Otherwise it would get written to the binary file as well and corrupt it.

If you have multiple scriptlet blocks, then you need to arrange them so that there's no linebreak between the ending %> of a scriptlet and the starting <% of the next scriptlet. Thus, e.g.

<%@page import="java.io.InputStream" %><%
    //...
%>

instead of

<%@page import="java.io.InputStream" %>
<%
    //...
%>

You need to set the MIME type in the HTTP response like below in addition to the sample code you provided.

response.setContentType("application/octet-stream");

Note, the application/octet-stream MIME type is used to indicate a binary file.

Please, please, please don't do this.

You're doing a disservice to your users.

HTTP is amazingly rich in terms of what it can do with files. Caching, chunking, random access, etc.

Take a look at something like FileServlet, and hammer that to fit. Yes, it's a Servlet, rather than a JSP, but this is what you want to do to be a good HTTP citizen.

Some containers have other options you can use, you can hack Tomcats DefaultServlet, etc.

Something like this...

InputStream instr = null;
try {
    instr = new BufferedInputStream( new FileInputStream("file.txt") );
    for(int x=instr.read(); x!=-1; x=instr.read()){
        out.write(x);
    }
} finally {
    out.close();
    if( instr != null) instr.close();
}

You will need this as the response to the click (either on a page reload or in another jsp file).

There are better buffering solutions you can do with the write using byte arrays rather than one at a time... I will leave that for you.

Sorry you are stuck in JSP scriptlet land...Hope this helps.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!