We will go directly to the topic, file download only need four steps:
1. Set the file ContentType type
2. Setting the file header
3. Get Servletoutputstream object (out) via response
4. Write to the output stream (out)
Download code:
I'm using SPRINGMVC here, but the only purpose here is to get the ServletContext object, the object's purpose, as explained in the following example
Download, need to use two jar package: Commons-fileupload.jar and Commons-io.jar
ImportOrg.springframework.stereotype.Controller; Importorg.springframework.web.bind.annotation.RequestMapping; ImportOrg.springframework.web.context.ServletContextAware; ImportJavax.servlet.ServletContext; ImportJavax.servlet.ServletOutputStream; ImportJavax.servlet.http.HttpServletResponse; ImportJava.io.*; @Controller Public classFilecontrollerImplementsservletcontextaware{//Spring here is to inject ServletContext objects by implementing the Servletcontextaware interface PrivateServletContext ServletContext; @RequestMapping ("File/download") Public voidFileDownload (httpservletresponse response) {//Gets the site deployment path (via the ServletContext object), which is used to determine the download file location for downloadString Path = Servletcontext.getrealpath ("/"); //1. Set the file contenttype type, this setting, will automatically determine the download file typeResponse.setcontenttype ("Multipart/form-data"); //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=" + "A.pdf"); Servletoutputstream out; //get the file object through the path of the files (false there is a download.pdf file in this path)File File =NewFile (path + "download/" + "Download.pdf"); Try{FileInputStream InputStream=Newfileinputstream (file); //3. Get Servletoutputstream object (out) via responseout =Response.getoutputstream (); intb = 0; byte[] buffer =New byte[512]; while(b! =-1) {b=inputstream.read (buffer); //4. Write to the output stream (out)Out.write (buffer,0, B); } inputstream.close (); Out.close (); Out.flush (); } Catch(IOException e) {e.printstacktrace (); }} @Override Public voidSetservletcontext (ServletContext servletcontext) { This. ServletContext =ServletContext; } }
File download (simple four steps required), common in Java