ICode9

精准搜索请尝试: 精确搜索
首页 > 编程语言> 文章详细

Java下载多个网络文件并打成压缩包

2021-11-29 11:34:48  阅读:158  来源: 互联网

标签:Java java 打成 IOException conn new import logger 压缩包


需求:浏览器访问后台的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的地址,即可直接下载压缩包。

 

标签:Java,java,打成,IOException,conn,new,import,logger,压缩包
来源: https://www.cnblogs.com/dreamboy/p/15618579.html

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有