java browser file download package method

Recently, the project encountered a series of pictures need to download the package needs, drawing on some of the common methods of online, on the way to share out the method to achieve, I do not remember learn who is calling brothers blog, in short, very grateful , that is entered, the basic functions package to download:

1.controller level code:

    / ** 
     * Image compression package 
     * / 
    @ RequestMapping (value = "/ the ZipFile" )
     public  void compressionFile (Request the HttpServletRequest, HttpServletResponse the Response, String busiId) throws Exception {
         // business code, the query to the resource table according to the front desk came ID image List 
        SubMetaData subMetaData = subMetaDataService.findByBusiId (busiId);
         IF (! subMetaData = null ) { 
            List <SubMetaDataAtt> List = subMetaDataAttService.findByDataId (subMetaData.getDataId ());
             IF (list.size ()> 0 ) {
                subMetaDataAttService.downloadAllFile(request,response,list);
            }
        }
    }    

2.service layer common file download package

/ ** 
     * multiple file compression package, to solve the garbage problem after downloading the file name 
     * 
     * / 
    public  void downloadAllFile (Request the HttpServletRequest, HttpServletResponse the Response, List <SubMetaDataAtt> List) throws UnsupportedEncodingException { 
        String downloadName = "attached images .zip " ; 
        String the userAgent = request.getHeader (" the User-- Agent " );
         // for IE or IE as the browser kernel: 
        IF (userAgent.contains (" MSIE ") || userAgent.contains (" Trident " )) { 
            downloadName = java.net.URLEncoder.encode (downloadName, "UTF-. 8" );
        } else {
            //Dealing with non-IE browser: 
            downloadName = new new String (downloadName.getBytes ( "UTF-8"), "ISO-8859-1" ); 
        } 
// After the above process name to solve the garbage problem after downloading the file name 
        the response.setContentType ( "multipart / form-Data" ); 
        response.setCharacterEncoding ( "UTF-. 8" ); 
        response.setHeader ( "the Content-Disposition", String.format ( "Attachment; filename = \"% S \ "" , downloadName));
         // response.setHeader ( "the Content-Disposition", "Attachment; fileName =" + downloadName); 
        the OutputStream the outputStream = null ;
        ZipOutputStream = null ;
        the try { 
            the outputStream = response.getOutputStream (); 
            ZOS = new new the ZipOutputStream (the outputStream);
             // file stream writing the zip, this method posted below 
            downloadTolocal (ZOS, List); 
        } the catch (IOException E) { 
            Logger. error ( "Download all attachments downloadAllFile- failed" , E); 
        } the finally {
             IF (ZOS =! null ) {
                 the try { 
                    zos.close (); 
                } the catch (Exception E2) {
                    logger.info ( "Error occurred while closing the input stream" , E2); 
                } 
            } 
            IF (the outputStream =! null ) {
                 the try { 
                    ; outputStream.close () 
                } the catch (Exception E2) { 
                    logger.info ( "off input stream error " , e2); 
                } 
            } 

        } 

    }

Write files in the zip method:

Private  void downloadTolocal (ZOS ZipOutputStream, List <SubMetaDataAtt> list) throws IOException {
         // get file information // here is business code, can be replaced according to their needs, I'm here is to get the resource table list circulation path and file name, and then into ZipEntry in before the download. 
        for (SubMetaDataAtt subMetaDataAtt: List) { 
            String fileId = subMetaDataAtt.getAttId (); 
            String fileName = subMetaDataAtt.getFileAlias () + subMetaDataAtt.getFileSuffixName (); 
            String path = subMetaDataAtt.getFileAbsolutePath (); 
            the InputStream IS = null ; 
            BufferedInputStream in =null ;
             byte [] Buffer = new new  byte [1024 ];
             int len;
             // create a zip entity (a file corresponding to a the ZipEntry) 
            the ZipEntry entry = new new the ZipEntry (fileName);
             the try {
                 // Get the stream file to be downloaded 
                File file = new new File (path);
                 IF (File.Exists ()) { 
                    IS = new new the FileInputStream (File); 
                } 
                in = new new BufferedInputStream (IS);
                zos.putNextEntry (entry); 
                // file stream write cycle the ZipOutputStream 
                the while ((len = in.read (Buffer)) = -1! ) { 
                    zos.write (Buffer, 0 , len); 
                } 
            } the catch (Exception E ) { 
                logger.info ( "Download all attachments - archive error" , E); 
            } the finally {
                 IF ! (entry = null ) {
                     the try { 
                        zos.closeEntry (); 
                    } the catch (Exception E2) { 
                        logger.info ( " Download all attachments --zip entity failed to close " , e2);
                    } 
                } 
                IF (! In = null ) {
                     the try { 
                        in.close (); 
                    } the catch (Exception E2) { 
                        logger.info ( "Download all attachments - Close file input stream failed" , E2); 
                    } 
                } 
                IF (IS ! = null ) {
                     the try { 
                        is.close (); 
                    } the catch (Exception E) { 
                        logger.info ( "Download all attachments - Close stream input buffer failed" , E);
                    }
                }


            }

        }

3. js request reception method:

Note: Do not download files to use AJAX request, so is unable to respond to the request, generally using Window.open approach.

window.open (context + "/ Sub / submetadataatt / the ZipFile busiId =?" + downloadId); // here downloadId is a variable I need to spread the background.

Summary: Operating on upload, download, in fact, be very familiar with java's IO, before they can play the turn, we must grasp the foundation can navigate in the project, not something I need to learn from others, we Working together, come on!

 

Guess you like

Origin www.cnblogs.com/adolph2715/p/11094809.html