Implementation of Servlet File Download Function

Source: Internet
Author: User

What about the Servlet File Download function? In Servlet/JSP, how does one use HTTP Protocol to implement dynamic file download service. This function is used in system development and has encountered several problems. I want to share my experience with you and hope to help you.

1. Problems with ms ie version

 
 
  1. If (request. getHeader ("User-Agent"). indexOf ("MSIE 5.5 ")! =-1 ){
  2.  
  3. // MS IE5.5 has to be specially handled
  4.  
  5. Response. setHeader ("Content-Disposition ",
  6.  
  7. "Filename= "+ New String (f_name.getBytes (" Big5 "),"ISO8859_1"));
  8.  
  9. }
  10.  
  11. Else {
  12.  
  13. // Non-IE5.5 Header setting method
  14.  
  15. Response. addHeader ("Content-Disposition ",
  16.  
  17. "Attachment;Filename= "+ New String (f_name.getBytes (" Big5 "),"ISO8859_1"));
  18.  
  19. }

In IE 5.5, the keyword attachment cannot be added. This is a strange version.

2. download the Chinese file name, such as the syntax in the previous program block. You can simply change the file name to "ISO8859_1" encoding. I have tested Tomcat, Oracle 9ias, sun One can download the document name normally, and the advantage is that no package is required.

3. After the file is downloaded, add the following two lines of commands:

Response. setStatus (response. SC _ OK );

Response. flushBuffer ();

These two lines have not been added before, and can often be added in error. the error message "Connection rest by peer" is displayed in the log. What's more serious is that the servlet/jsp to be downloaded will not end. It takes a long time to get Timeout, if the number of downloads is large, the AP Server will be miserable. Therefore, it is best to add these two lines of commands to a program for dynamic file download.

4. For security considerations, sometimes the Write Program is lazy and uses dumpfile. jsp? F_name = attach/a.txt. If the name parameter of the uploaded file is not filtered out in the program, it cannot be mixed with "..", imagine if someone intentionally changes the parameter to this? Dumpfile. jsp? F_name =.../../a.txt, hey, all the files in the system have been downloaded.

These two lines have not been added before, and can often be added in error. the error message "Connection rest by peer" is displayed in the log. What's more serious is that the servlet/jsp to be downloaded will not end. It takes a long time to get Timeout, if the number of downloads is large, the AP Server will be miserable. Therefore, it is best to add these two lines of commands to a program for dynamic file download.

5. For security considerations, sometimes the Write Program is lazy and uses dumpfile. jsp? F_name = attach/a.txt. If the name parameter of the uploaded file is not filtered out in the program, it cannot be mixed with "..", imagine if someone intentionally changes the parameter to this? Dumpfile. jsp? F_name =.../../a.txt, hey, all the files in the system have been downloaded.

The above are all the mistakes I have made. For your reference.

 
 
  1. import java.io.*;  
  2. import java.util.*;  
  3. import javax.servlet.*;  
  4. import javax.servlet.http.*;  
  5.  
  6. public classDownload extends HttpServlet  
  7. {  
  8. public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException  
  9. {  
  10. try  

// Here you can do other things

 
 
  1. Response. setContentType ("application/octet-stream ");
  2. Response. setHeader ("Content-Disposition", "attachment;Filename= \ "The name of the saved file to be displayed in the SAVE window \"");
  3.  
  4. ServletOutputStreamOut=Response. GetOutputStream ();
  5. BufferedReaderBr=NewBufferedReader (new FileReader (name of the file to be downloaded ));
  6.  
  7. StringLine=Br. ReadLine ();
  8. While (line! = Null)
  9. {
  10. Out. write (line. getBytes ());
  11. Out. println ();
  12. Line=Br. ReadLine ();
  13. }
  14. Out. close ();
  15. Br. close ();
  16. }
  17. Catch (Exception e)
  18. {
  19. System. out. println (e );
  20. }
  21. }
  22. Public void doPost (HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException
  23. {
  24. DoGet (request, response );
  25. }
  26. }

That's simple.

Note: To solve the problem, change BIG5 In the first reference to GBK:

New String (name. getBytes ("GBK"), "ISO8859_1 ")

There is a problem with the code downloaded above. Only character-class files can be downloaded. errors may occur in binary files. Use the following code instead.

 
 
  1. BufferedInputStream in = null;  
  2. ServletOutputStream out = null;  
  3. FileInputStream stream = null;  
  4. try {  
  5. out = response.getOutputStream();  
  6. stream = new FileInputStream(file);  
  7.  
  8. int bytesRead = 0;  
  9. final int length = 8192;  
  10. byte[] buffer = new byte[length];  
  11. while ((bytesRead = stream.read(buffer, 0, length)) != -1) {  
  12. // write at server side  
  13. out.write(buffer, 0, bytesRead);  
  14. }  
  15. } catch (IOException e) {  
  16. throw new BPDBusiException(  
  17. ResourceConst.SCORECARD_ERR_DOWNLOADATTACHMENT_DOWNLOAD);  
  18. } finally {  
  19. if (in != null) {  
  20. in.close();  
  21. }  
  22. if (out != null) {  
  23. out.close();  
  24. }  

The implementation of the Servlet File Download function is actually a call of some methods. It is helpful for your development idea to explain the Implementation of The Servlet File Download function.

  1. At the beginning of JSP Servlet Development
  2. Enhanced Servlet and JSP security without modifying code
  3. Servlet and JSP paths
  4. How to Improve Servlet and JSP Application Efficiency
  5. Functions and principles of several encodings in JSP and Servlet

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.