java web bulk download

Posted by wemustdesign on Thu, 30 Apr 2020 16:08:10 +0200

java batch download, package multiple files into zip format to download

What we need now:

Download the pic package under the product family and product type according to the product family and product type;

pic package is a zip file;

Table:

These packages exist in another table as blob s:

T? Imagefile table:

Now what we need to do is: download the two packages under the access network and OLT: MA5800 series pic.zip and ma5900 pic.rar into ZIP compressed files and download them;

code:

ProductController.java:

  /**
     * Download photo package according to product family and product type
     */
    @RequestMapping("/downloadwBatch")
    public void downloadwBatch(HttpServletRequest request, HttpServletResponse response, String productFamily, String productType){
        //Http: / / localhost: 8080 / mysm / downloadbatch? Productfamily = access network & ProductType = OLT
        try {
            productFamily = new String(productFamily.getBytes("iso-8859-1"), "utf-8");
            productType = new String(productType.getBytes("iso-8859-1"), "utf-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        
        //Get the name of the photo package to download
        Map<String, String> params = new HashMap<String, String>();
        params.put("productFamily", productFamily);
        params.put("productType", productType);
        List<String> packageNames = productService.getPackageNamesByFamilyAndType(params);
        
        //Get the format of the file name byte array to be downloaded according to the package name
        Map<String, byte[]> files = new HashMap<String, byte[]>();
        for(String packageName : packageNames){
            byte[] f = productService.getPackage(packageName);
            if(f!=null){
                files.put(packageName, f);
            }
        }
        
        //Set the name of the downloaded package
        String zipName = productFamily + "_"+ productType + ".zip";
        
        //According to the file, compress and download in batch
        if(files.size() > 0){
            productService.downloadBatchByFile(response, files, zipName);
        }
        
    }


ProductService.java:

  /**
     * Get files by package name
     */
    public byte[] getPackage(String packageName){
        byte[] bag  = null;
        try{
            ImageFile m = productMapper.getPackage(packageName);
            if(m!=null){
                bag = m.getPicture();
            }
        }catch(Exception e){
            e.printStackTrace();
        }
        return bag;
    }
    
    
    /**
     * Obtain package name to be downloaded according to product family and product type
     * @param params
     * @return
     */
    public List<String> getPackageNamesByFamilyAndType(Map<String, String> params) {
        List<String> packageNames = productMapper.getPackageNamesByFamilyAndType(params);
        
        return packageNames;
    }
    
    /**
     * According to the file, compress and download in batch
     * @param response
     * @param files
     * @throws Exception 
     */
    public void downloadBatchByFile(HttpServletResponse response, Map<String, byte[]> files, String zipName){
        try{
            response.setContentType("application/x-msdownload");
            response.setHeader("content-disposition", "attachment;filename="+URLEncoder.encode(zipName, "utf-8"));
            
            ZipOutputStream zos = new ZipOutputStream(response.getOutputStream());
            BufferedOutputStream bos = new BufferedOutputStream(zos);
            
            for(Entry<String, byte[]> entry : files.entrySet()){
                String fileName = entry.getKey();            //Each zip file name
                byte[]    file = entry.getValue();            //Bytes of this zip file
                
                BufferedInputStream bis = new BufferedInputStream(new ByteArrayInputStream(file));
                zos.putNextEntry(new ZipEntry(fileName));
                
                int len = 0;
                byte[] buf = new byte[10 * 1024];
                while( (len=bis.read(buf, 0, buf.length)) != -1){
                    bos.write(buf, 0, len);
                }
                bis.close();
                bos.flush();
            }
            bos.close();
        }catch(Exception e){
            e.printStackTrace();
        }
    }

ProductMapper.java:

    /**
     * Get files by package name
     */
    public ImageFile getPackage(String packageName) throws Exception;

    /**
     * Obtain package name to be downloaded according to product family and product type
     */
    public List<String> getPackageNamesByFamilyAndType(Map<String, String> params);


ProductMapper.xml:

 <!-- Get files by package name -->
    <select id="getPackage" parameterType="java.lang.String" resultType="com.cy.model.ImageFile">
        select * from t_imagefile where packageName = #{packageName}
    </select>
    
    <!--  Obtain package name to be downloaded according to product family and product type -->
    <select id="getPackageNamesByFamilyAndType" parameterType="java.util.Map" resultType="java.lang.String">
        select packageName from t_imagefile m join t_product p on m.packageName = p.downloadPic
        where p.productFamily = #{productFamily} and p.productType = #{productType}
    </select>

Test:

In the browser, enter: http: / / localhost: 8080 / mysm / downloadbatch? Productfamily = access network & ProductType = OLT

The download results are as follows:

Simple demo

package com.msznyl;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
public class Download {
    public static void main(String[] args) {
        //Files to be compressed -- including file address and file name
        String [] path ={"E:\\360DocProtect\\01.txt","E:\\360DocProtect\\02.docx"};
        // Compressed file address and file name to generate
        String desPath = "D:\\DOWNLOADS\\new.zip";
        File zipFile = new File(desPath);
        ZipOutputStream zipStream = null;
        FileInputStream zipSource = null;
        BufferedInputStream bufferStream = null;
        try {
            //Construct the output stream of the final compressed package
            zipStream = new ZipOutputStream(new FileOutputStream(zipFile));
            for(int i =0;i<path.length;i++){
                File file = new File(path[i]);
              //Format files to be compressed as input streams
                zipSource = new FileInputStream(file);
                //The compressed item is not a specific independent file, but a list item in the compressed package file list. It is called an item, just like an index
                ZipEntry zipEntry = new ZipEntry(file.getName());
                //Locate the compressed entry location and start writing files to the compressed package
                zipStream.putNextEntry(zipEntry);

             //Input buffer stream
             bufferStream = new BufferedInputStream(zipSource, 1024 * 10);
             int read = 0;
             //Create read write buffer
             byte[] buf = new byte[1024 * 10];
             while((read = bufferStream.read(buf, 0, 1024 * 10)) != -1)
            {
                zipStream.write(buf, 0, read);
            }
            }
          
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
                //Close flow
                try {
                    if(null != bufferStream) bufferStream.close();
                    if(null != zipStream) zipStream.close();
                    if(null != zipSource) zipSource.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
        }
    }
} 

Topics: Java network xml