Example tutorials for implementing file downloads in Java Web projects _java

Source: Internet
Author: User

Requirements: To achieve a file download function of the Web page, the main download compression package and pictures
Two methods of implementation:

One: Download via hyperlink
in an HTML Web page, link to the address of the file you want to download through a hyperlink

<! DOCTYPE html> 
 
 

Where Day06/download is the document path, the program structure of this instance is as follows:

After the program is run, you can download it by clicking the document you want to download

But there will be a problem, that is, when you click the download package will pop up the download page, but download the picture when the browser directly opened the picture, did not download.

This is because when you download a file through a hyperlink, if the browser can recognize the file format, the browser opens directly. Downloads are only implemented when the browser does not recognize the file format. So the second method is used to implement the download function.

Second: Through the servlet program to achieve download
the principle of downloading files through the servlet is to read the target program through the servlet and return the resource to the client.

<! DOCTYPE html> 
 
 

Where/day06/servletdownload is the mapping path of the servlet program
Then create a new servlet with the name Servletdownload,url mapped to/servletdownload

Add the following code:

Package com.lsgjzhuwei.servlet.response; 
Import Java.io.FileInputStream; 
Import Java.io.FileOutputStream; 
Import java.io.IOException; 
Import Java.io.InputStream; 
 
Import Java.io.OutputStream; 
Import javax.servlet.ServletException; 
Import Javax.servlet.annotation.WebServlet; 
Import Javax.servlet.http.HttpServlet; 
Import Javax.servlet.http.HttpServletRequest; 
 
Import Javax.servlet.http.HttpServletResponse; /** * Servlet Implementation class Servletdownload/@WebServlet (asyncsupported = true, Urlpatterns = {"/servletdow 
     
  Nload "}) public class Servletdownload extends HttpServlet {private static final long serialversionuid = 1L; 
    /** * @see httpservlet#httpservlet () * * * Public servletdownload () {super (); TODO auto-generated Constructor stub}/** * @see httpservlet#doget (httpservletrequest request, HttpServlet Response Response) */protected void doget (HttpServletRequest request, HttpServletResponse Response) throWS Servletexception, IOException {//TODO auto-generated Method Stub//GET request filename String filename = req 
    Uest.getparameter ("filename"); 
     
    SYSTEM.OUT.PRINTLN (filename); 
    Sets the file MIME type Response.setcontenttype (Getservletcontext (). GetMimeType (filename)); 
    Set Content-disposition response.setheader ("Content-disposition", "attachment;filename=" +filename);  Read the target file and write the target file to the client//get the absolute path of the target file by response String Fullfilename = Getservletcontext (). Getrealpath ("/download/" + 
    filename); 
    System.out.println (Fullfilename); 
    Read file InputStream in = new FileInputStream (fullfilename); 
     
    OutputStream out = Response.getoutputstream (); 
    Write file int b; 
    while ((B=in.read ())!=-1) {out.write (b); 
    } in.close (); 
  Out.close (); /** * @see Httpservlet#dopost (httpservletrequest request, httpservletresponse response) * * Protected Voi D DoPost (httpservletrequest request, HttpseRvletresponse response) throws Servletexception, IOException {//TODO auto-generated method stub}} 
 

Restart the Tomcat server to implement the compression package and the download of the picture.

Third, the small skill:
Click on the link to download the file is simple, the background of the file flow output, through the browser to achieve the download function, including query location and file storage, most browsers will be configured a fixed location, not necessarily every time ask.

The front end is very simple, a <a> tag, href= "Background method Address", if your needs can not be directly linked to the way to write in js window.location.href = "Background method address."

After this jump to the background method

 String FilePath = This.getclass (). getClassLoader (). GetResource (""). Touri (). GetPath ( ) + "/exportpdf.pdf";
    The file is in the project path file outfile = new file (FilePath);
          String filename = outfile.getname ()//Get file name InputStream FIS = new Bufferedinputstream (New FileInputStream (
    FilePath)); 
    byte[] buffer = new byte[fis.available ()]; Fis.read (buffer);
    Read file stream fis.close (); Response.reset ();  Resets the result set Response.AddHeader ("Content-disposition", "attachment;filename=" + New String (Filename.replaceall (""), ""). GetBytes ("Utf-8"), "iso8859-1")); Returns the header filename Response.AddHeader ("Content-length", "" "+ Outfile.length ());  Returns the header file size Response.setcontenttype ("Application/octet-stream"); 
    Set data type//Get return body output outputstream OS = new Bufferedoutputstream (Response.getoutputstream ()); Os.write (buffer);
    Output file Os.flush ();
Os.close (); 

The

Browser directly recognizes this form of file output and pops up a dialog box.
Note that this method must be linked to the background, using AJAX and XMLHttpRequest methods are not, so that the return of the file stream will return to the method of the callback function, of course, if you want to get the file in JS, this will do.

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.