Java Bulk Compression Download

Source: Internet
Author: User
Tags save file

Recently did some about the volume compression download the function, the net also looked for some resources, but is not too comprehensive, therefore oneself organizes a copy, has prepared a contingency.

Directly on the code:

Get Project Path
private static String Webclass_path = Thread.CurrentThread (). Getcontextclassloader (). GetResource (""). GetPath ();
Get Webinf Path
private static String Webinf_path = webclass_path.substring (0, Webclass_path.lastindexof ("classes"));
Get Upload Path
private static String Upload_path = webinf_path.substring (0, Webinf_path.lastindexof ("Web-inf")) + "upload/";

  Public voidDownloadallfiles (httpservletrequest request, httpservletresponse response) {//gets the information for the file to be downloaded id-selected file ID concatenation of stringsString lessionidstr = Request.getparameter ("Fileids"); //filename of first fileString firstfilename = ""; List<UploadFileInfo> Downloadfiles =NewLinkedlist<uploadfileinfo>(); if(Stringutil.isnotempty (lessionidstr)) {intEnd = Lessionidstr.lastindexof (","); if(End > 0) {                if(End = = Lessionidstr.length ()-1) {Lessionidstr= lessionidstr.substring (0, end); } string[] IDs= Lessionidstr.split (",");  for(inti = 0; i < ids.length; i++) {                    //loop to get each file informationUploadfileinfo FileInfo =Uploadfileinfoservice.selectbyprimarykey (Ids[i]); if(FileInfo! =NULL) {downloadfiles.add (fileInfo); }                    if(i = = 0) {Firstfilename= Fileinfo.getfilename (). substring (0, Fileinfo.getfilename (). LastIndexOf (".")); }                }            }Else {                //loop to get each file informationUploadfileinfo FileInfo =Uploadfileinfoservice.selectbyprimarykey (LESSIONIDSTR); if(FileInfo! =NULL) {downloadfiles.add (fileInfo); } firstfilename= Fileinfo.getfilename (). substring (0, Fileinfo.getfilename (). LastIndexOf (".")); }        }                //There are data to download        if(Downloadfiles.size ()! = 0) {            //for preprocessingpreprocess (firstfilename, response); //Compression ProcessingWritezip (downloadfiles); //Download FileDownfile (response); //Delete Temporary Compressed filesafterprocess (); }    }        //compressed file output stream    PrivateZipoutputstream out; //Temporary compressed file storage path    PrivateString FilePath; /*** Description: Preprocessing * Parameters:@paramfirsefilename First file name * parameter for bulk download:@paramResponse*/    Private voidpreprocess (String firsefilename, httpservletresponse response) {//Compressed file nameString zipname = "Bulk Download" "+ Firsefilename +" and so on. zip "; FilePath= Upload_path +Zipname; Try {            //initializing the compressed file output streamout =NewZipoutputstream (NewFileOutputStream (FilePath)); //empty the output stream (the Thunder download will not appear a long channeling)Response.reset (); //set the response header and the client save file nameResponse.setcharacterencoding ("Utf-8"); Response.setcontenttype ("Multipart/form-data"); //!! New String (Zipname.getbytes ("GBK"), "8859_1") if the file contains Chinese, it must be converted, otherwise the downloaded file name is garbled formatResponse.setheader ("Content-disposition", "attachment;filename=" +NewString (Zipname.getbytes ("GBK"), "8859_1")); } Catch(IOException e) {e.printstacktrace (); }    }        /*** Description: Compression processing * Parameters:@paramdownloadfiles file data collection for bulk download*/    Private voidWritezip (list<uploadfileinfo>downloadfiles) {        byte[] buf =New byte[2048]; intLen = 0; Try {             for(Uploadfileinfo fileinfo:downloadfiles) {//Get upload fileFile File =NewFile (upload_path.substring (0, Upload_path.lastindexof ("UPLOAD")) +Fileinfo.getfilepath ()); if(!File.isfile ()) {                    Continue; }                    //Set EncodingOut.setencoding (System.getproperty ("sun.jnu.encoding")); //set the compressed file nameZipEntry ze =NewZipEntry (Fileinfo.getfilename ()); //adding to the output streamout.putnextentry (ze); //Read and output the source fileFileInputStream FIS =Newfileinputstream (file);  while(len = Fis.read (BUF))! =-1) {out.write (buf,0, Len); }                    //Refresh (must have)Out.flush ();                    Out.closeentry ();            Fis.close (); }            if(Out! =NULL) {out.close (); }        } Catch(IOException e) {e.printstacktrace (); }      }        /*** Description: Download Temporary Compressed files * Parameters:@paramResponse*/    Private voidDownfile (httpservletresponse response) {Try{File File=NewFile (FilePath); if(File.exists ()) {InputStream ins=NewFileInputStream (FilePath); //put it inside the buffer stream .Bufferedinputstream bins =Newbufferedinputstream (INS); //get file output io streamOutputStream outs =Response.getoutputstream (); Bufferedoutputstream Bouts=NewBufferedoutputstream (outs); intBytesread = 0; byte[] buffer =New byte[1024]; //start transferring file streams to the network                 while((bytesread = bins.read (buffer))! =-1) {bouts.write (buffer,0, Bytesread); }                //Be sure to call the Flush () method hereBouts.flush ();                Ins.close ();                Bins.close ();                Outs.close ();            Bouts.close (); }        } Catch(IOException e) {logger.error ("File Download Error", E); }       }        /*** Description: Delete Temporary compressed files*/    Private voidafterprocess () {//Delete source FilesFile tempzip=NewFile (FilePath); if(Tempzip.exists ()) {tempzip.delete (); }    }    

Java Bulk Compression Download

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.