common file Download in Java (ContentType, header, response, out four steps)
Sina Weibo: It Imperial College (remember to follow OH) Http://weibo.com/itguozijian
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 ServletContext objects by implementing the Servletcontextaware interface
- Private ServletContext ServletContext;
- @RequestMapping ("File/download")
- public void FileDownload (HttpServletResponse response) {
- Gets the site deployment path (via the ServletContext object), which is used to determine the download file location for download
- String Path = Servletcontext.getrealpath ("/");
- 1. Set the file contenttype type, this setting, will automatically determine the download file type
- Response.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 = new file (path + "download/" + "download.pdf");
- try {
- FileInputStream InputStream = new FileInputStream (file);
- 3. Get Servletoutputstream object (out) via response
- out = Response.getoutputstream ();
- int b = 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 void Setservletcontext (ServletContext servletcontext) {
- This.servletcontext = ServletContext;
- }
- }
Common file Download in Java (ContentType, header, response, out four steps)