Java File download feature issue resolution log

Source: Internet
Author: User

Today to the report system to do a download function, encountered a lot of problems, through the search for information one by one solved.

1, first encountered the problem is: Java background output stream output, there is no error, the browser does not pop up to save the file dialog box, originally AJAX request to the back-end controller method added the download method, type and async two parameters of four combinations are not, Discard Ajax, with window.location.href= ' file/download?path= ' +file; after re-sending a new download request, the Save dialog box finally pops up.

2, after the popup, found that the file name is garbled, the solution code of the background is as follows:

     private static final String CHARSET = "Utf-8";        

String agent = Request.getheader ("user-agent" ). toLowerCase (); if (Agent! = null && ( Agent.indexof ("MSIE")! =-1 | | (Agent.indexof ( "rv")! =-1 && agent.indexof ("Firefox") = = -1 = Urlencoder.encode (File.getname (), "UTF-8" ); else {fileName = new String (File.getname (). GetBytes (CHARSET), "iso8859-1" ); }

3, the backstage has been in error getwriter () has already been calledfor this response, through the error content can probably see servletoutputstream out = Response.getoutputstream (); This should be a singleton, but there is no other place in the call this method to get the output stream, carefully testing the discovery, each time all requests are closed, the first time there will be no problem, then the request will be an error, Put the back out.close (); Comment out, the error will be solved.

4. The method of the foreground spelling file path

                varfile; varPath = $ ("#lujing"). Val (); if(Path.lastindexof (' \ \ ')!=path.length-1){                    //Console.info ("Do not end with slashes");File = $ ("#lujing"). Val () + "\ \" + $ ("#city"). Val () + "city" + $ ("#year1"). Val ()+ $ ("#month1"). Val () + "e-commerce data analysis report. doc"; } Else {                    //Console.info ("End with Slash");File = $ ("#lujing"). Val () + $ ("#city"). Val () + "city" + $ ("#year1"). Val ()+ $ ("#month1"). Val () + "e-commerce data analysis report. doc"; } window.location.href= ' file/download?path= ' +file;

5. Export Controller

ImportJava.io.File;ImportJava.io.FileInputStream;Importjava.io.IOException;Importjava.io.UnsupportedEncodingException;ImportJava.net.URLEncoder;ImportJavax.servlet.ServletOutputStream;ImportJavax.servlet.http.HttpServletResponse;Importjavax.servlet.http.HttpServletRequest;ImportOrg.springframework.stereotype.Controller;Importorg.springframework.web.bind.annotation.RequestMapping;/** * @authorAuthor Jeffy *@version  *  */@Controller Public classfilecontroller{//Spring here is to inject ServletContext objects by implementing the Servletcontextaware interface    Private Static FinalString CHARSET = "Utf-8"; @RequestMapping ("/exportreport/file/download")       Public Static voidFileDownload (httpservletresponse response, httpservletrequest request, String Path)throwsunsupportedencodingexception{File File=NewFile (path);        String FileName; String Agent= Request.getheader ("User-agent"). toLowerCase (); if(Agent! =NULL&& (Agent.indexof ("MSIE")! =-1 | |(Agent.indexof ("RV")! =-1 && agent.indexof ("Firefox") = = = 1)) {fileName= Urlencoder.encode (File.getname (), "UTF-8"); } Else{fileName=NewString (File.getname (). GetBytes (CHARSET), "Iso8859-1"); }//Response.reset ();//very Important//1. Set the file contenttype type, this setting, will automatically determine the download file typeResponse.setcontenttype ("Multipart/form-data"); Response.setcontenttype ("Application/octet-stream;charset=utf-8"); //2. Set the file header: The last parameter is to set the download file name (if we call A.pdf)Response.setheader ("Content-disposition", "attachment;filename=" +fileName);        Servletoutputstream out; Try{FileInputStream InputStream=Newfileinputstream (file); //3. Get Servletoutputstream object (out) via responseout =Response.getoutputstream (); intb = 0; byte[] buffer =New byte[512];  while((b = inputstream.read (buffer))! =-1){                  //4. Write to the output stream (out)Out.write (buffer,0, B);  } inputstream.close (); //Out.close (); //Out.flush ();         } Catch(IOException e) {e.printstacktrace (); }      }  }

The above is the Java file download all the problems encountered, there may be no test of the problem, the follow-up found the problem in a timely manner, but also ask you a lot of criticism.

Java File download feature issue resolution log

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.