Java Web-side program implementation file download method sharing _java

Source: Internet
Author: User
Tags java web

There are two types of Web file downloads, one is the file in the Web site directory, in the browser directly enter the file path can be downloaded, such as Http://www.xxx.com/file.zip. The other is that the file is not in the site directory or the file is dynamically generated (export reports or export Excel, etc.), this situation requires the response OutputStream implementation of the file download. Downloadutils is a Java web file Download tool class that provides a variety of static methods to implement file downloads.

Package com.rhui.util; 
Import Java.io.BufferedInputStream; 
Import Java.io.BufferedOutputStream; 
Import Java.io.File; 
Import Java.io.FileInputStream; 
Import java.io.IOException; 
Import Java.io.InputStream; 
Import Java.io.OutputStream; 
 
Import Java.net.URLEncoder; 
 
Import Javax.servlet.http.HttpServletResponse; 
 
Import Org.apache.commons.lang3.StringUtils; /** * File Download class */public class Downloadutils {/** * File download code * This code tells the browser file name encoding, in case of downloading Chinese file name is garbled * * * * privat 
   
  e static String encoding = "Utf-8"; /** * File Download * @param response * @param filePath file path on the server, including filename/public static void Download (Httpserv 
    Letresponse response, String filePath) {File File = new file (filepath.tostring ()); 
  Download (response, file, null, encoding); /** * File Download * @param response * @param filePath files on the server path, including file name * @param filename File download to the browser name, if If you do not want the browser to download the same file name as the file name on the server, set this parameter/public static void Download (HttpservLetresponse response, String FilePath, String fileName) {File File = new file (filepath.tostring ()); 
  Download (response, file, FileName, encoding); /** * File Download * @param response * @param filePath files on the server path, including file name * @param filename File download to the browser name, if If you do not want the browser to download the same file name as the file name on the server, set the parameter * @param encoding file name encoding/public static void download (HttpServletResponse re 
    Sponse, String FilePath, String fileName, string encoding) {File File = new file (filepath.tostring ()); 
  Download (response, file, FileName, encoding); /** * File Download * @param response * @param file * @param fileName file download to the browser name, if you do not want to let the browser download the file name and the server File name, please set this parameter/public static void Download (httpservletresponse response, file file) {Download (Response, fil 
  E, NULL, encoding); /** * File Download * @param response * @param file * @param fileName file download to the browser name, if you do not want to let the browser download the file name and the server File name, please set this parameter/public static void DowNload (httpservletresponse response, file file, String filename) {Download (response, file, filename, encoding); /** * File Download * @param response * @param file * @param fileName file download to the browser name, if you do not want to let the browser download the file name and the server File name, please set this parameter * @param encoding file name encoding/public static void Download (httpservletresponse response, file file, 
    String FileName, String encoding {if (file = = NULL | |!file.exists () | | | file.isdirectory ()) {return; 
    //If you do not specify the name of the file to download to the browser, use the default name of the file if (Stringutils.isblank (fileName)) {filename = File.getname (); 
      The try {InputStream is = new FileInputStream (file); 
    Download (response, is, fileName, encoding); 
    catch (IOException e) {e.printstacktrace (); }/** * File download * @param response * @param is file input stream * @param filename downloaded file name * @throws Ioexc Eption */public static void Download (HttpServletResponse response, InputStream is, String fileName) {Download (response, is, filename, encoding); /** * File Download * @param response * @param is file input stream * @param filename Download file name * @param encoding encoding 
    Format */public static void Download (HttpServletResponse response, InputStream is, string fileName, string encoding) { if (is = = NULL | | 
    Stringutils.isblank (FileName)) {return; 
    } Bufferedinputstream bis = null; 
    OutputStream OS = null; 
     
    Bufferedoutputstream BOS = NULL; 
      try{bis = new Bufferedinputstream (IS); 
      OS = Response.getoutputstream (); 
      BOS = new Bufferedoutputstream (OS); 
      Response.setcontenttype ("application/octet-stream;charset=" + encoding); 
      response.setcharacterencoding (encoding); 
      Response.setheader ("Content-disposition", "attachment;filename=" + urlencoder.encode (filename, encoding)); 
      byte[] buffer = new byte[1024]; 
      int len = bis.read (buffer); while (Len!=-1) {Bos.writE (buffer, 0, Len); 
      Len = bis.read (buffer); 
    } bos.flush (); 
    }catch (IOException e) {e.printstacktrace (); 
        }finally{if (bis!= null) {try{bis.close (); 
        }catch (IOException e) {}} if (is!= null) {try{is.close (); 
  }catch (IOException e) {}}} public static String GetEncoding () {return encoding; 
  The public static void Setencoding (String encoding) {downloadutils.encoding = encoding; 

 } 
}

If the file is saved in the server's non-web directory

String FilePath = "C:\\file.zip"; 
Downloadutils.download (response, FilePath); 

If the file is an input stream

is the file input stream 
//filename for the browser to download the file name 
//encoding for the file name code, to prevent the file in the Chinese language produced garbled 
String fileName = "File.zip"; 
String encoding = "Utf-8"; 
Downloadutils.download (response, is, fileName, encoding); 

File downloads in servlet

Package com.rhui.web.servlet; 
 
Import java.io.IOException; 
 
Import javax.servlet.ServletException; 
Import Javax.servlet.annotation.WebServlet; 
Import Javax.servlet.http.HttpServlet; 
Import Javax.servlet.http.HttpServletRequest; 
Import Javax.servlet.http.HttpServletResponse; 
 
Import Com.rhui.util.DownloadUtils; 
 
@WebServlet ("/download/servlet") public 
class Downloadservlet extends HttpServlet { 
  private static final long Serialversionuid = 1L; 
   
  protected void Service (HttpServletRequest request, httpservletresponse response) throws Servletexception, IOException { 
    String FilePath = "C:\\file.zip"; 
    Downloadutils.download (response, FilePath); 
  } 
 
 

PS: Picture download (including anti-theft chain function)

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);
 }
 
}

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.