JAVA_通过URL获取文件,进行打包返回zip的字节流


后端


controller

public void downloadFiles(@RequestBody @Valid Req<DownloadFilesDto> requestDTO, HttpServletResponse response) throws Exception {

    byte[] zipBytes = prpmUploadImageService.downloadFiles(requestDTO.getData());
    String filename = requestDTO.getData().getCaseNo() +"_"+ requestDTO.getData().getLossId()+".zip";
    response.setContentType(MediaType.APPLICATION_OCTET_STREAM_VALUE);

    StringBuilder contentDispositionValue = new StringBuilder();
    contentDispositionValue.append("attachment; filename=")
            .append(filename)
            .append(";")
            .append("filename*=")
            .append("utf-8''")
            .append(filename);

    response.setHeader("Access-Control-Expose-Headers","filename");
    response.setHeader("Content-disposition", contentDispositionValue.toString());
    response.setHeader("filename",filename);
    IoUtil.write(response.getOutputStream(),true,zipBytes);
}

service

byte[] downloadFiles(DownloadFilesDto downloadFilesDto) throws Exception;

serviceImpl

@Override
public byte[] downloadFiles(DownloadFilesDto downloadFilesDto) throws Exception {
   try {
       //模拟从数据库查出多张图片路径
       String[] urlArr = new String[]{
               "图片链接1",
               "图片链接2"
       };
       ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
       ZipOutputStream zip = new ZipOutputStream(outputStream);

       Map<String,Integer> repeatMap = new ConcurrentHashMap<>();
       for (String url : urlArr) {
           //下载查出的图片
           String path = IdUtils.randomUUID()+".png";
           byte[] bytes = IOUtils.toByteArray(new URL(url));
           ZipUtils.append(zip,bytes, path,repeatMap);
       }
       IOUtils.closeQuietly(zip);
       byte[] zipBytes = outputStream.toByteArray();
       return zipBytes;

   } catch (IOException e) {
       e.printStackTrace();
   }
}

工具类

package org.apache.commons.io.IOUtils
package cn.hutool.core.io.IoUtil
@Slf4j
public class ZipUtils extends ZipUtil {

    @SneakyThrows
    public static void append(ZipOutputStream zip, byte[] bytes, String path){
        zip.putNextEntry(new ZipEntry(path));
        IOUtils.write(bytes, zip);
    }

    @SneakyThrows
    public static void append(ZipOutputStream zip, byte[] bytes, String path, @NotNull Map<String,Integer> repeatMap){
        if(repeatMap == null){
            repeatMap = new ConcurrentHashMap<>();
        }
        if(repeatMap.containsKey(path)){
            String fileName = FileUtil.getName(path);
            log.info("重复文件,路径:{},文件名:{},重新命名",path,fileName);
            Integer index = repeatMap.get(path);
            index = (index == null?0:index) + 1;
            repeatMap.put(path,index);

            String namePrefix = FileUtil.getPrefix(fileName);
            String nameSuffix = FileUtil.getSuffix(fileName);
            fileName = namePrefix + "(" + index +")." +nameSuffix;
            path = path(path) + fileName;
            log.info("重复文件重新命名后,路径:{},文件名:{}",path,fileName);
            repeatMap.put(path,0);
        }else{
            repeatMap.put(path,0);
        }
        zip.putNextEntry(new ZipEntry(path));
        IOUtils.write(bytes, zip);
    }

    public static String path(String fileName) {
        if (null == fileName) {
            return null;
        } else {
            int len = fileName.length();
            if (0 == len) {
                return fileName;
            } else {
                if (CharUtil.isFileSeparator(fileName.charAt(len - 1))) {
                    --len;
                }

                int begin = 0;
                int end = len;

                String prefix = FileUtil.getName(fileName);

                return fileName.substring(begin, end - prefix.length());
            }
        }
    }
}

前端

js部分

引入后端接口

export function download(data) {
  return request({
    url: '/survey/image/downloadFiles',
    method: 'post',
    data: data,
    responseType: 'blob'
  })
}

方法调用接口

downloadFile(){
  download(obj).then((res)=>{
    const binaryData = []
    binaryData.push(res)// res 后台返回的流数据
    this.url = window.URL.createObjectURL(new Blob(binaryData, { type: 'application/zip;charset-UTF-8' }))
    window.open(this.url)        
  })
},
  • 0
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Java中可以使用`java.util.zip`包来实现根据URL将多个文件打包zip进行下载的功能。下面是一个示例代码: ```java import java.io.*; import java.net.URL; import java.util.zip.ZipEntry; import java.util.zip.ZipOutputStream; public class FileZipDownloader { public static void main(String[] args) { String zipUrl = "http://example.com/files.zip"; String[] fileUrls = {"http://example.com/file1.txt", "http://example.com/file2.txt"}; try { // 创建ZipOutputStream FileOutputStream fos = new FileOutputStream("downloaded_files.zip"); ZipOutputStream zos = new ZipOutputStream(fos); // 从URL下载并添加文件zip中 for (String fileUrl : fileUrls) { URL url = new URL(fileUrl); InputStream is = url.openStream(); zos.putNextEntry(new ZipEntry(url.getFile())); byte[] buffer = new byte[1024]; int length; while ((length = is.read(buffer)) > 0) { zos.write(buffer, 0, length); } is.close(); zos.closeEntry(); } // 关闭流 zos.close(); fos.close(); // 下载zip文件 downloadZip(zipUrl); } catch (IOException e) { e.printStackTrace(); } } private static void downloadZip(String url) throws IOException { URL zipUrl = new URL(url); InputStream is = zipUrl.openStream(); FileOutputStream fos = new FileOutputStream("downloaded_files.zip"); byte[] buffer = new byte[1024]; int length; while ((length = is.read(buffer)) > 0) { fos.write(buffer, 0, length); } is.close(); fos.close(); } } ``` 上述代码首先创建了一个`ZipOutputStream`对象,然后依次遍历多个文件URL,将每个文件下载后添加到zip中,并关闭流。最后调用`downloadZip`方法根据zip文件URL进行下载。请确保提供的URL文件格式的可用性和正确性。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值