【原创】url转字节码导出压缩包

public void exportBatch(HttpServletResponse response,HttpServletRequest request,List<String> urls) {

        try {
            UrlFilesToZip s = new UrlFilesToZip();
            List<ByteFileBean> fileBeans = new ArrayList<>();
            for (int i = 0; i < urls.size ; i++) {
                byte[] bytes = s.getImageFromURL(url);
                ByteFileBean byteFileBean = new ByteFileBean();
                byteFileBean.setFileName("文件夹" + i + File.separator+s.getFileName(url);
                byteFileBean.setFileContent(bytes);
                fileBeans.add(byteFileBean);
            }
            //控制文件名编码
            String filename = s.encodeChineseDownloadFileName(request,"xxx.zip");
            s.downLoadFilesToZip(fileBeans, filename, request, response, response.getOutputStream());
        } catch (FileNotFoundException ex) {
            log.error("FileNotFoundException", ex);
            throw new GenericException(BusCodeEnum.BATCH_DOWN_LOAD_FILE_FAIL.getCode(),BusCodeEnum.BATCH_DOWN_LOAD_FILE_FAIL.getMsg());
        } catch (Exception ex) {
            log.error("Exception", ex);
            throw new GenericException(BusCodeEnum.BATCH_DOWN_LOAD_FILE_FAIL.getCode(),BusCodeEnum.BATCH_DOWN_LOAD_FILE_FAIL.getMsg());
        }
    }
@Getter
@Setter
@NoArgsConstructor
@AllArgsConstructor
@SuppressFBWarnings
public class ByteFileBean {
    /**
     * 文件名
     */
    private String fileName;

    /**
     * 文件内容,byte数组
     */
    private byte[] fileContent;
}
public class UrlFilesToZip {

    /**
     * 根据文件链接把文件下载下来并且转成字节码
     * @param urlPath
     * @return byte[]
     */
    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) {
            log.error("MalformedURLException", e);
        } catch (IOException e) {
            log.error("IOException", e);
        } finally {
            try {
                if (is != null) {
                    is.close();
                }
            } catch (IOException e) {
                log.error("IOException", e);
            }
            assert conn != null;
            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) {
            log.error("IOException", e);
        }
        byte[] data = baos.toByteArray();
        try {
            is.close();
            baos.close();
        } catch (IOException e) {
            log.error("IOException", e);
        }
        return data;
    }



    /**
     * 从url获取文件名
     * @param url
     * @return
     * @throws IOException
     */
    public  String getFileName(String url){

        return url.substring(url.lastIndexOf('/') + 1);
    }

	/**
     * 防止中文乱码
     * @param request
     * @param fileName
     * @return String 
     */
    public  String encodeChineseDownloadFileName(HttpServletRequest request, String fileName) throws Exception {

        String newFileName = null;
        String agent = request.getHeader("USER-AGENT");
        if (null != agent) {
            if (-1 != agent.indexOf("Firefox")) {//Firefox
                newFileName =
                        "=?UTF-8?B?" + (new String(org.apache.commons.codec.binary.Base64.encodeBase64(fileName.getBytes(
                                "UTF-8")))) + "?=";
            } else if (-1 != agent.indexOf("Chrome")) {//Chrome
                newFileName = new String(fileName.getBytes(), "ISO8859-1");
            } else {//IE7+
                newFileName = java.net.URLEncoder.encode(fileName, "UTF-8");
                newFileName = newFileName.replace("+", "%20");
            }
        } else {
            newFileName = fileName;
        }
        return newFileName;
    }

	
	/**
     * 批量下载文件并打包成zip
     * @param fileBeans
     * @param zipName
     * @return String 
     */
    public  void downLoadFilesToZip(List<ByteFileBean> fileBeans, String zipName,
                                          HttpServletRequest request, HttpServletResponse response,
                                          OutputStream outputStream) throws GenericException {
        if (fileBeans == null || fileBeans.isEmpty()) {
            throw new GenericException(BusCodeEnum.DOWN_LOAD_FILES_IS_NULL.getCode(),
                    BusCodeEnum.DOWN_LOAD_FILES_IS_NULL.getMsg());
        }
        if (com.catxcloud.core.util.StringUtils.isBlank(zipName)) {
            throw new GenericException(BusCodeEnum.ZIP_NAME_IS_NULL.getCode(),
                    BusCodeEnum.ZIP_NAME_IS_NULL.getMsg());
        }
        String zipNameAlias;
        try {
            //转化为小写
            zipNameAlias = zipName.toLowerCase();
        } catch (Exception e) {
            zipNameAlias = zipName;
        }
        String encodeName;
        //如果含有.zip了
        if (zipNameAlias.endsWith(".zip")) {
            encodeName = com.catxcloud.core.util.StringUtils.substringBeforeLast(zipName, ".");
        } else {
            encodeName = zipName;
        }

        ZipArchiveOutputStream zous;
        try {
            if (outputStream == null) {
                outputStream = response.getOutputStream();
            }
            zous = new ZipArchiveOutputStream(outputStream);
            zous.setUseZip64(Zip64Mode.AsNeeded);
            //编码zip文件名并加上后缀(压缩包内部文件名不需要编码)
            String newZipName = encodeChineseDownloadFileName(request, encodeName) + ".zip";
            //设置应答头
            response.setHeader("Content-disposition", "attachment; filename=" + newZipName);
        } catch (Exception e) {
            throw new GenericException(BusCodeEnum.BATCH_DOWN_LOAD_FILE_FAIL.getCode(),
                    BusCodeEnum.BATCH_DOWN_LOAD_FILE_FAIL.getMsg());
        }

        //读取所有文件,一个失败则跳过
        for (ByteFileBean bean : fileBeans) {
            if (bean == null) {
                continue;
            }
            if (com.catxcloud.core.util.StringUtils.isBlank(bean.getFileName())) {
                Log.error("[批量下载文件并打包成zip服务]当前文件文件名为空,无法下载");
                continue;
            }
            //如果内容为空也不能下载
            if (bean.getFileContent() == null || bean.getFileContent().length == 0) {
                Log.error("[批量下载文件并打包成zip服务]文件名为:" + bean.getFileName() + "的文件,文件内容为空无法下载");
                continue;
            }

            try {
                ArchiveEntry entry = new ZipArchiveEntry(bean.getFileName());
                zous.putArchiveEntry(entry);
                zous.write(bean.getFileContent(), 0, bean.getFileContent().length);
                zous.closeArchiveEntry();
            } catch (Exception e) {
                Log.error("[批量下载文件并打包成zip服务]文件名为:" + bean.getFileName() + "的文件打进zip出错", e);
            }
        }
        try {
            if (zous != null) {
                zous.flush();
                zous.close();
            }
        } catch (Exception e) {
            Log.error("[批量下载文件并打包成zip服务]出错", e);
            throw new GenericException(BusCodeEnum.BATCH_DOWN_LOAD_FILE_FAIL.getCode(),
                    BusCodeEnum.BATCH_DOWN_LOAD_FILE_FAIL.getMsg());
        }
    }
}
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值