Java Web application Implementation of the basic file download function of the example explained _java

Source: Internet
Author: User
Tags java web

Basic ideas:
the previous idea has been to pop a box to ask the user where they want to store the file, and then I'll regenerate it into a file. However, I did not succeed in this idea.
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 requirements can not be directly linked to the way, you can 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 (Filepa
  th)); 
  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 ("", ""). G Etbytes ("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 will directly recognize this form of file output, pop-up 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 files in JS, this will do.


instance

Package cn.itcast.day06.web.servlet;
Import java.io.IOException;
Import Java.io.InputStream;
Import Java.io.OutputStream;
 
Import Java.net.URLEncoder;
Import Javax.servlet.ServletContext;
Import javax.servlet.ServletException;
Import Javax.servlet.http.HttpServlet;
Import Javax.servlet.http.HttpServletRequest;
 
Import Javax.servlet.http.HttpServletResponse; public class Downloadservlet extends HttpServlet {public void doget (HttpServletRequest request, HttpServletResponse re Sponse) throws Servletexception, IOException {//Implement anti-theft chain function//Get referer header to indicate where the visitor came from String referer = Request.geth
 Eader ("Referer");
  if (Referer==null | |!referer.startswith ("http://localhost")) {//Is hotlinking response.sendredirect ("/day06/index.jsp");
 return; //Solve Response Chinese garbled problem Response.setcontenttype ("Text/html;charset=utf-8");
 
 Set the message body's encoding//HTTP response message headers sent through the HTTP protocol cannot appear Chinese must go through URL encoding String filename = Urlencoder.encode ("Belle. jpg", "utf-8"); Notifies the browser to read the resource Response.setheader the way it is downloaded("Content-disposition", "attachment;filename=" +filename); Read picture data to IE browser String webpath = "/download/beauty. jpg";
 
 The path ServletContext ServletContext = Super.getservletcontext () equivalent to the current Web application;
 
 
 InputStream in = Servletcontext.getresourceasstream (Webpath);
 
 
 OutputStream out = Response.getoutputstream ();
 int Len;
 byte[] buffer = new byte[1024];
 
 while ((Len=in.read (buffer))!=-1) out.write (buffer, 0, Len); 
 public void DoPost (HttpServletRequest request, httpservletresponse response) throws Servletexception, IOException {
 Doget (request, response);
 }
 
}

Related Article

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.