开发者

JSP: I am doing an application in which i have to download ppt file

I am working on an application wherein I have to download a PPT file using a JSP page. I am using the following code, but it's not working.

<% try {
   String filename = "file/abc.ppt";

   // set the http content type to "APPLICATION/OCTET-STREAM
   response.setContentType("APPLICATION/OCTET-STREAM");

   // initialize the http content-disposition header to
   // indicate a file attachment with the default filename
   // "myFile.txt"
   String disHeader = "Attachment Filename=\"abc.ppt\"";

   response.setHeader("Content-Disposition", disHeader);

   // transfer the file byte-by-byte to the response object
   File fileToDownload = new File(filename);
   FileInputStream fileInputStream = new
      FileInputStream(fileToDownload);
   int i;
   while ((i=fileInputStream.read())!=-1)
   {
      out.write(i);
   }
   fileInputStream.close();
   out.close();
   }catch(Exception e) // file IO errors
   {
   e.pri开发者_JS百科ntStackTrace();
}
%>

Can anybody solve this problem?


Not only the Content-Disposition header is incorrect, but you're incorrectly using JSP instead of a Servlet for this particular task.

JSP is a view technology. Everything outside the scriptlets <% %> will be printed to the response, including whitespace characters such as newlines. It would surely corrupt binary files.

You could trim the whitespace in the JSP file, but scriptlets are discouraged since a decade and nowadays considered bad practice. Raw Java code belongs in Java classes, not in JSP files. The real solution is to use a HttpServlet for this.

Create a class which extends HttpServlet, implement the doGet() method, move the Java code from the JSP file into this method, map this servlet on a certain url-pattern and your problem should disappear. You can find here a basic example of such a servlet.


Off the top there should be a semicolon in the Content-Disposition header ("attachment*;* filename ...)

You should also probably do a response.reset() before starting to set headers and stream. Internet Explorer has really strange rules about streaming files from secure sockets and won't work right if you don't clear the caching headers.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜