Java File download function code (single file download, multi-file Bulk package download)--Universal application

Source: Internet
Author: User
Tags create zip create zip file int size

First, the preface
Programmers in the web and other projects, often need to add files to upload, download, delete the function, sometimes a single file, sometimes multiple file bulk operations, and these features of the code programmers can collect their own as a tool to use, so that programmers in the process of programming will be more than a multiplier, The next blog will explain how to use the file upload and download functions for each frame.
This blog focus on the various frameworks can be applicable to the file download function code, not to say more directly into the topic:

Second, the example

1. The general need to join the jar package:
Commons.fileupload-1.2.1.jar and Commons.io-1.4.0.jar, click to download jar packs

2. Examples of methods:

Normal Java File download method, applicable to all framework public void DownloadFile () throws ioexception{//Get file root directory, different frames to get the same way, you can freely switch String b  

    Asepath = Request.getsession (). Getservletcontext (). Getrealpath ("/upload/text");  

    Gets the file name (including file format) String fileName = Request.getparameter ("Downfilename");  

    Combined into a full file path String TargetPath = Basepath+file.separator+filename;  
    Simulate more than one file, used to test multiple-file bulk download String targetPath1 = basepath+file.separator+ "Ggg.jpg";  
    SYSTEM.OUT.PRINTLN ("FileName:" +filename);  

    System.out.println ("File path:" +targetpath); Method 1:io Stream Implementation of the download function HttpServletResponse res = GetResponse (); Create response Response Res.setcontenttype ("text/html; Charset=utf-8 "); Sets the encoding character res.setcontenttype ("Application/x-msdownload"); Set content type to download type Res.setheader ("Content-disposition", "attachment;filename=" +filename);/set downloaded file name OutputStream o   UT = Res.getoutputstream ();  
    Create a page return mode for the output stream, will automatically eject the download box//method 1-1:io byte stream load, for small file System.out.println ("Byte stream load"); InPutstream is = new FileInputStream (TargetPath);  Create file input stream byte[] Buffer = new byte[2048];  Sets the size of each read data, that is, the cache size int size = 0; Used to calculate whether the cached data has been read, and if the data has been read, return-1 while ((Size=is.read (Buffer)!=-1) {//loop read the data and return-1 if the data is read Out.writ E (Buffer, 0, size);  
    Writes each read of data to the client}/*//method 1-2:io character streaming, for large file System.out.println ("character stream");  File File = new file (TargetPath);  Create file FileInputStream fis=new FileInputStream (TargetPath); Creates a file byte input stream bufferedinputstream buff=new bufferedinputstream (FIS);  Create a file buffer input stream byte [] b=new byte[2048];  Sets the size of each read long l=0; Used to determine whether the length of the file is equivalent to the file download size while (L<file.length ()) {//loop read the file int j=buff.read (b,0,2048);  
        Length l+=j; Out.write (B,0,J);//* Write cache to client}////Method 1-3: Compress multiple files in attachment, bulk package download file//Create empty Zip bundle String for compressed file Zipbas  
    Epath=request.getsession (). Getservletcontext (). Getrealpath ("/upload/zip/"); String Zipfilepath = zipbasepath+ "Temp.zip";  
    Creates a collection of file paths, list<string> FilePath = new arraylist<string> ();  
    Filepath.add (TargetPath);  

    Filepath.add (TARGETPATH1);  
    Creates the zip file, file Zip = new file (Zipfilepath), based on the temporary ZIP compression package path;     
    if (!zip.exists ()) {zip.createnewfile ();  
    //Create zip file output stream FileOutputStream fos = new FileOutputStream (Zip);  

    Zipoutputstream Zos = new Zipoutputstream (FOS);  Iterates through the file path collection to get the path for each file for (String fp:filepath) {file F = new file (FP);  Creates a file based on the file path ZipFile (f, Zos);  
    Write each file into a ZIP file package, which is packaged} fos.close ();  

    Zos.close ();  
    The packaged file is written to the client and the output method is the same, using the buffered stream output InputStream fis = new Bufferedinputstream (new FileInputStream (Zipfilepath));  
    byte[] buff = new byte[4096];  
    int size = 0;  
    while ((Size=fis.read (Buff))!=-1) {out.write (buff, 0, size);  
    ///release and close the input/output stream//out.flush ();  
    Out.close (); FIs.close ();  
    Buff.close ();  
Is.close (); }//Encapsulation compressed file method public void ZipFile (file Inputfile,zipoutputstream zipoutputstream) {try {if (Inputfile.exists ())  
                    {//Determine if the file exists if (Inputfile.isfile ()) {//judge whether it belongs to a file or folder//create input stream read file  
                    FileInputStream fis = new FileInputStream (inputfile);  

                    Bufferedinputstream bis = new Bufferedinputstream (FIS); Writes a file into a zip, packaging the file zipentry ze = new ZipEntry (Inputfile.getname ());     

                    Gets the filename zipoutputstream.putnextentry (ze);  
                Method of writing the file, Ibid. Byte [] b=new byte[1024];  
                Long l=0;  
                    while (L<inputfile.length ()) {int j=bis.read (b,0,1024);  
                    L+=j;  
                Zipoutputstream.write (B,0,J); //Close Input lossOut Flow bis.close ();  
                Fis.close (); else {//If it is a folder, get the file using the exhaustive method, write the zip try {file[] files = inputfile.listf  
                        Iles ();  
                        for (int i = 0; i < files.length i++) {ZipFile (files[i), zipoutputstream);  
                    } catch (Exception e) {e.printstacktrace ();  
        catch (Exception e) {e.printstacktrace ()}}};   }  
}

Third, summary

1. This method combines the word throttling, character streams for single file and multiple file packaging download, Methods 1-1, Methods 1-2 and 1-3 respectively belong to different forms of download methods, are based on Method 1 operations, three methods can not be used at the same time, need to use which type of method to remove the annotation can be;

2, practice is to test the truth of the only standard, according to code and comment More to try, you will soon understand the principle


Previous: Jfinal absolute path and Action Request path add folder name to cause "404 Not Found" problem

Next: SSH framework of the Springmvc file download function code

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.