java从文件服务器oss上读取文件,并导出压缩文件(.ZIP)

前端接收类型设置为blob

axios.defaults.responseType = 'blob'

后端

设置编码

response.setContentType("application/json");
response.setHeader("Content-disposition", "attachment; filename=" + URLEncoder.encode("contract_files.zip", "UTF-8"));
ZipOutputStream zipOut = new ZipOutputStream(response.getOutputStream());//方法调用
Result result = factorContractService.exportZip(projNoList, zipOut);
response.flushBuffer();
zipOut.close();
/**
 * 压缩文件
 *
 * @param
 * @param
 * @param
 * @throws IOException
 */
public static void zipFile( String relationId,List uploadAttachmentModels,ZipOutputStream zipOut) throws IOException {
    //如果是文件夹的话
    String folderName = relationId+"/";
    zipOut.putNextEntry(new ZipEntry(folderName));
    zipOut.closeEntry();
    if (!CollectionUtils.isEmpty(uploadAttachmentModels)) {
        for (UploadAttachmentModel uploadAttachment : uploadAttachmentModels) {
            String fileUrl = uploadAttachment.getUrl();
            //对异常url进行处理
            fileUrl = fileUrl.substring(0, fileUrl.lastIndexOf('?'));
            LOGGER.info("进行下载的url为:{}", fileUrl);
            URL url = new URL(fileUrl);
            // 打开连接
            URLConnection con = url.openConnection();
            // 输入流
            InputStream in = con.getInputStream();
            zipOut.putNextEntry(new ZipEntry(folderName+uploadAttachment.getName()));
            byte[] bytes = new byte[1024];
            int len;
            while ((len = in.read(bytes)) != -1) {
                zipOut.write(bytes, 0, len);
            }
            in.close();
            zipOut.closeEntry();
        }
    }

}

你可能感兴趣的:(java杂谈)