Java 线上文件进行合成zip并进行下载

package com.cpiaoju.manage.bank.controller;


import com.cpiaoju.manage.bank.entity.YhCompanyAuth;
import com.cpiaoju.manage.bank.entity.ZxlrAuditLog;
import com.cpiaoju.manage.bank.entity.ZxlrProductConfig;
import com.cpiaoju.manage.bank.service.YhCompanyAuthService;
import com.cpiaoju.manage.bank.service.ZxlrAuditLogService;
import com.cpiaoju.manage.common.entity.SupplyResponse;
import com.cpiaoju.manage.common.utils.*;
import io.swagger.annotations.ApiOperation;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.net.URLEncoder;
import java.util.*;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author lxg
 * @since 2021-10-08
 */
@RestController
@RequestMapping("/bank/zxlr-audit-log")
public class ZxlrAuditLogController {

    @Autowired
    private ZxlrAuditLogService auditLogService;
    @Autowired
    private YhCompanyAuthService companyAuthService;

    /**
     * @Description 根据id查询审核数据详情
     * @Author lxg
     * @Param [productConfig, request]
     * @Return com.cpiaoju.manage.common.entity.SupplyResponse
     **/
    @GetMapping("/view")
    public SupplyResponse view(Integer id) {
        return new SupplyResponse().success().data(auditLogService.view(id));
    }

    /**
     * @Description 新增数据
     * @Author lxg
     * @Param [productConfig, imgArray]
     * @Return com.cpiaoju.manage.common.entity.SupplyResponse
     **/
//    @ManageLog(LogEnum.COMMUNITY_BBS_MANAGEMENT_SERVICE_ADD)
    @PostMapping("/add")
    public SupplyResponse add(ZxlrAuditLog auditLog, HttpServletRequest request) {
        auditLogService.add(auditLog,request);
        return new SupplyResponse().success().message("新增成功");
    }

    /**
     * 上传文件
     *
     */
    @PostMapping("/auth")
    public SupplyResponse auth(MultipartFile authPdfFile) throws IOException {

        return new SupplyResponse().success().data(auditLogService.auth(authPdfFile));
    }

    /**
     *
     * 下载文件
     * @param response
     * @param url
     */
    @GetMapping("/downloadUrlFile")
    public void downloadUrlFile(HttpServletResponse response,String url){
        try {
            FileUtil.downloadUrlFile(response,url);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     *
     */
    @GetMapping("/batchDownload")
    public void batchDownload(HttpServletResponse response,Integer id) throws IOException{


        int index = 1;
        String strIndex;
        String zipName ="企业资料.zip";
        response.setContentType("application/octet-stream");
        response.setHeader("content-disposition","attachment;filename=" + URLEncoder.encode(zipName, "UTF-8"));
        ZipOutputStream zos = new ZipOutputStream(response.getOutputStream());
        StringBuilder sb;
        InputStream inputStream;
        byte[] by;
        // 企业名/合同一/发票/发票1.png
        sb = new StringBuilder();
        sb.append("/");
        StringBuilder str;

        Map<String, Object> view = companyAuthService.view(id);

        if(!CommUtil.isEmpty(view.get("font_id_url"))){
            boolean contains =view.get("font_id_url").toString().contains("http");
         if (contains){
            str = new StringBuilder(sb.toString());
            zos.putNextEntry(new ZipEntry(str.append("fontIdUrl").append(CommUtil.getFileType((String) view.get("font_id_url"))).toString()));
            inputStream = HttpURLConnectionUtil.getInputStreamByGet((String) view.get("font_id_url"));
            by = CommUtil.GetImageStrFromUrl(inputStream);
            zos.write(by, 0, by.length);
            zos.closeEntry();
            }

        }

        if(!CommUtil.isEmpty(view.get("back_legal_url"))) {
            boolean contains =view.get("back_legal_url").toString().contains("http");
            if (contains) {
                str = new StringBuilder(sb.toString());
                zos.putNextEntry(new ZipEntry(str.append("back_legal_url").append(CommUtil.getFileType((String) view.get("back_legal_url"))).toString()));
                inputStream = HttpURLConnectionUtil.getInputStreamByGet((String) view.get("back_legal_url"));
                by = CommUtil.GetImageStrFromUrl(inputStream);
                zos.write(by, 0, by.length);
                zos.closeEntry();
            }
        }

            zos.close();






    }


	public static byte[] GetImageStrFromUrl(InputStream inputStream) {
		ByteArrayOutputStream bos = new ByteArrayOutputStream();
		byte[] data  =null;
		try {
			byte[] by = new byte[1024];
			// 创建链接
			InputStream is = inputStream;
			// 将内容读取内存中
			int len = -1;
			while ((len = is.read(by)) != -1) {
				bos.write(by, 0, len);
			}
			data = bos.toByteArray();
			// 关闭流
			is.close();
			bos.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return data;
	}

    	/**
	 * 通过文件名判断并获取OSS服务文件上传时文件的contentType
	 * @param fileName 文件名
	 * @return 文件的contentType
	 */
	public static String getFileType(String fileName) {
		// 文件的后缀名
		String fileExtension = fileName.substring(fileName.lastIndexOf("."));
		if (".jpeg".equalsIgnoreCase(fileExtension)) {
			return ".jpeg";
		}
		if (".jpg".equalsIgnoreCase(fileExtension)) {
			return ".jpg";
		}
		if (".png ".equalsIgnoreCase(fileExtension)) {
			return ".png";
		}
		if (".pdf".equalsIgnoreCase(fileExtension)) {
			return ".pdf";
		}
		if (".bmp".equalsIgnoreCase(fileExtension)) {
			return ".bmp";
		}
		if (".gif".equalsIgnoreCase(fileExtension)) {
			return ".gif";
		}
		if (".html".equalsIgnoreCase(fileExtension)) {
			return ".html";
		}
		if (".txt".equalsIgnoreCase(fileExtension)) {
			return ".plain";
		}
		if (".vsd".equalsIgnoreCase(fileExtension)) {
			return ".vnd.visio";
		}
		if (".ppt".equalsIgnoreCase(fileExtension) || "pptx".equalsIgnoreCase(fileExtension)) {
			return ".vnd.ms-powerpoint";
		}
		if (".doc".equalsIgnoreCase(fileExtension) || "docx".equalsIgnoreCase(fileExtension)) {
			return ".msword";
		}
		if (".xml".equalsIgnoreCase(fileExtension)) {
			return ".xml";
		}
		// 默认返回类型
		return ".jpg";
	}


    public static InputStream getInputStreamByGet(String url) {
        try {
            HttpURLConnection conn = (HttpURLConnection) new URL(url)
                    .openConnection();
            conn.setReadTimeout(5000);
            conn.setConnectTimeout(5000);
            conn.setRequestMethod("GET");

            if (conn.getResponseCode() == HttpURLConnection.HTTP_OK) {
                InputStream inputStream = conn.getInputStream();
                return inputStream;
            }

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

    // 将服务器响应的数据流存到本地文件
    public static boolean saveData(InputStream is, File file) {
        try (BufferedInputStream bis = new BufferedInputStream(is);
             BufferedOutputStream bos = new BufferedOutputStream(
                     new FileOutputStream(file));) {
            byte[] buffer = new byte[1024];
            int len = -1;
            while ((len = bis.read(buffer)) != -1) {
                bos.write(buffer, 0, len);
                bos.flush();
            }
            return true;
        } catch (IOException e) {
            e.printStackTrace();
            return false;
        }
    }


}

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值