How to serve a file with JSP?

后端 未结 4 1922
一个人的身影
一个人的身影 2021-01-17 23:56

This may sound totally stupid, but is a case of real life :(

I\'m able to display a HTML table with a \"virtual\" link name.

Something like this:

         


        
相关标签:
4条回答
  • 2021-01-18 00:41

    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.

    0 讨论(0)
  • 2021-01-18 00:45

    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.

    0 讨论(0)
  • 2021-01-18 00:52

    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.

    0 讨论(0)
  • 2021-01-18 00:55

    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" %>
    <%
        //...
    %>
    
    0 讨论(0)
提交回复
热议问题