Java下載多個網絡文件並打成壓縮包


需求:瀏覽器訪問后台的http地址后,后台將多個網絡文件打成壓縮包返回給瀏覽器,用戶可以通過瀏覽器直接下載壓縮包。

實現:

根據文件鏈接把文件下載下來並且轉成字節碼  ,代碼:

package com.zwy.blog.servelt;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

public class UrlFilesToZip {
//    private static final Logger logger = LoggerFactory.getLogger(UrlFilesToZip.class);  
    //根據文件鏈接把文件下載下來並且轉成字節碼  
    public byte[] getImageFromURL(String urlPath) {  
        byte[] data = null;  
        InputStream is = null;  
        HttpURLConnection conn = null;  
        try {  
            URL url = new URL(urlPath);  
            conn = (HttpURLConnection) url.openConnection();  
            conn.setDoInput(true);  
            // conn.setDoOutput(true);  
            conn.setRequestMethod("GET");  
            conn.setConnectTimeout(6000);  
            is = conn.getInputStream();  
            if (conn.getResponseCode() == 200) {  
                data = readInputStream(is);  
            } else {  
                data = null;  
            }  
        } catch (MalformedURLException e) {  
//            logger.error("MalformedURLException", e);  
        } catch (IOException e) {  
//            logger.error("IOException", e);  
        } finally {  
            try {  
                if (is != null) {  
                    is.close();  
                }  
            } catch (IOException e) {  
//                logger.error("IOException", e);  
            }  
            conn.disconnect();  
        }  
        return data;  
    }  
  
  
    public byte[] readInputStream(InputStream is) {  
        ByteArrayOutputStream baos = new ByteArrayOutputStream();  
        byte[] buffer = new byte[1024];  
        int length = -1;  
        try {  
            while ((length = is.read(buffer)) != -1) {  
                baos.write(buffer, 0, length);  
            }  
            baos.flush();  
        } catch (IOException e) {  
//            logger.error("IOException", e);  
        }  
        byte[] data = baos.toByteArray();  
        try {  
            is.close();  
            baos.close();  
        } catch (IOException e) {  
//            logger.error("IOException", e);  
        }  
        return data;  
    }  
}

新建DownFileServlet,調用上面的工具類,代碼如下:

package com.zwy.blog.servelt;

import java.io.ByteArrayOutputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class DownFileServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;
    public DownFileServlet() {
        super();
    }
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request,response);
    }
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        try {  
            //String filename = new String("xx.zip".getBytes("UTF-8"), "ISO8859-1");//控制文件名編碼  
            String fileName = URLEncoder.encode("證據材料.zip","UTF-8"); 
            ByteArrayOutputStream bos = new ByteArrayOutputStream();  
            ZipOutputStream zos = new ZipOutputStream(bos);  
            UrlFilesToZip s = new UrlFilesToZip();  
            String urls[]={"https://hr-minio.cas-air.cn/pdf-temp/001d535005784d3d8220e89d5ce4b3ab.pdf","https://hr-minio.cas-air.cn/pdf-temp/001ee146be864a848a04bef6abfb1a89.pdf"};
            for (String oneFile : urls) {  
                String filename=oneFile.substring(oneFile.lastIndexOf("/")+1);
                zos.putNextEntry(new ZipEntry(filename));
                byte[] bytes = s.getImageFromURL(oneFile);  
                zos.write(bytes, 0, bytes.length);  
                zos.closeEntry();  
            }  
            zos.close();  
            response.setContentType("application/force-download");// 設置強制下載不打開  
            response.addHeader("Content-Disposition", "attachment;fileName=" + fileName);// 設置文件名  
            OutputStream os = response.getOutputStream();  
            os.write(bos.toByteArray());  
            os.close();  
        } catch (FileNotFoundException ex) {  
//            logger.error("FileNotFoundException", ex);  
        } catch (Exception ex) {  
//            logger.error("Exception", ex);  
        }  
    }  
    

}

瀏覽器直接訪問DownFileServlet的地址,即可直接下載壓縮包。

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM