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
Java code
- Import Org.springframework.stereotype.Controller;
- Import org.springframework.web.bind.annotation.RequestMapping;
- Import Org.springframework.web.context.ServletContextAware;
- Import Javax.servlet.ServletContext;
- Import Javax.servlet.ServletOutputStream;
- Import Javax.servlet.http.HttpServletResponse;
- Import java.io.*;
- @Controller
- Public class Filecontroller implements servletcontextaware{
- //spring here is to inject the ServletContext object by implementing the Servletcontextaware interface
- private ServletContext ServletContext;
- @RequestMapping ("File/download")
- public void FileDownload (httpservletresponse response) {
- //Get Site Deployment path (via ServletContext object) to determine the location of the download file for download
- String path = Servletcontext.getrealpath ("/");
- //1. Set the file contenttype type so that it will automatically determine the type of download file
- Response.setcontenttype ("Multipart/form-data");
- //2. Setting 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;
- //The file object is obtained through the path of the files (false there is a download.pdf file in this path)
- File File = new file (path + "download/" + "download.pdf");
- try {
- FileInputStream InputStream = new FileInputStream (file);
- //3. Getting Servletoutputstream objects by response (out)
- out = Response.getoutputstream ();
- int b = 0;
- byte[] buffer = new byte[512];
- While (b! =-1) {
- b = inputstream.read (buffer);
- //4. Writing to the output stream (out)
- Out.write (buffer,0,b);
- }
- Inputstream.close ();
- Out.close ();
- Out.flush ();
- } catch (IOException e) {
- E.printstacktrace ();
- }
- }
- @Override
- public void Setservletcontext (ServletContext servletcontext) {
- this.servletcontext = ServletContext;
- }
- }
Java File download