0
点赞
收藏
分享

微信扫一扫

springboot生成zip文件并且输出byte[]

Soy丶sauce 2022-04-01 阅读 60

1.封装zip文件中的每个文件

 IpDesignerWorks designerWorkshop = ipDesignerWorksMapper.selectById(workshopId);
        if(designerWorkshop==null){
            return null;
        }
        String image = designerWorkshop.getImage();
        String s =image.substring(image.lastIndexOf("/")+1, image.lastIndexOf("."))+ image.substring(image.lastIndexOf("."));
        //zip文件中的各个文件 key 自定义名称 value 每个文件的byte数组
        HashMap<String, byte[]> inputStreamMap = new HashMap<>();
        inputStreamMap.put("形象-"+s,ZipUtil.getStream(image));
        JSONArray jsonArray = JSONArray.parseArray(designerWorkshop.getDigitalAsset());
        for (int i = 0; i < jsonArray.size(); i++) {
            JSONObject json = (JSONObject)jsonArray.get(i);
            String oldFileName = json.get("oldFileName").toString();
            inputStreamMap.put(
                    oldFileName.substring(oldFileName.lastIndexOf("/")+1, oldFileName.lastIndexOf("."))+"-"+i+
                            image.substring(image.lastIndexOf("."))
                    ,ZipUtil.getStream(json.get("newFilePath").toString()));
        }

//zip文件返回byte
        return ZipUtil.toZip2(inputStreamMap);

ZipUtil工具类:

package com.web.util;
import com.web.configurer.Base64PictureConfig;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.*;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

public class ZipUtil {
    private static final int BUFFER_SIZE = 2 * 1024;

   /*
   * 通过文件路径 http访问 返回改文件的byte信息
   * */
    public static byte[] getStream(String filePath) {
        try {
            //将文件路径进行http的url转码,不转则中文会判断为特殊字符
            filePath = getURLEncoderString(filePath);
            URL url = new URL(Base64PictureConfig.fileDownLoadPath+filePath);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setRequestMethod("GET");
            conn.setConnectTimeout(5 * 1000);
            InputStream inStream = conn.getInputStream();// 通过输入流获取图片数据
            byte[] btImg = readInputStream(inStream);// 得到图片的二进制数据
            return btImg;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }

    }
    /**
     * 从输入流中获取数据
     * @param inStream
     *            输入流
     * @return
     * @throws Exception
     */
    public static byte[] readInputStream(InputStream inStream) throws Exception {
        ByteArrayOutputStream outStream = new ByteArrayOutputStream();
        byte[] buffer = new byte[10240];
        int len = 0;
        while ((len = inStream.read(buffer)) != -1) {
            outStream.write(buffer, 0, len);
        }
        inStream.close();
        return outStream.toByteArray();
    }
    /*
    * 转义http中的字符
    * */
    public static String getURLEncoderString(String str) {
        String result = "";
        if (null == str) {
            return "";
        }
        try {
            result = java.net.URLEncoder.encode(str, "UTF-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        result = result.replaceAll("%2F","/");
        return result;
    }

    /**
     * 压缩成ZIP 方法
     * @return byte[] 文件流字节数组
     * @throws RuntimeException 压缩失败会抛出运行时异常
     */
    public static byte[] toZip2(HashMap<String, byte[]> inputStreamMap) throws RuntimeException, IOException {

        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        ZipOutputStream zipOut = new ZipOutputStream(baos);
        // --start
        Iterator<Map.Entry<String, byte[]>> iterator = inputStreamMap.entrySet().iterator();
        while (iterator.hasNext()){
            Map.Entry<String, byte[]> next = iterator.next();
            String key = next.getKey();
            ZipEntry entry = new ZipEntry(key);
            zipOut.putNextEntry(entry);
            byte[] value = next.getValue();
            zipOut.write(value);
        }
        // --end
        zipOut.close();
        byte[] bytes = baos.toByteArray();
        baos.close();// 关闭流
        return bytes;
    }
}
举报

相关推荐

0 条评论