java下载图片和表格的压缩包(图片按护工名字分文件夹)

  @Override
    public Page workerRecordList(Integer hospitalId, String searchStr, Date entryDate, Integer serviceAge, Integer state, Integer sex, Integer photo, Integer pageNo, Integer pageSize) {
        PageHelper.startPage(pageNo,pageSize);
        List data = workerRecordQueryManager.workerRecordList(hospitalId, searchStr, entryDate, serviceAge, state, sex, photo);
        Page page=new Page<>(data);

        // Page page = workerRecordQueryManager.workerRecordList(hospitalId, searchStr, entryDate, serviceAge, state, sex, photo, pageNo, pageSize);
        // List data = page.getData();

        //获取当前时间,在组里的护工
        long dateline = DateUtil.getDateline();
        String sql = "SELECT c.* FROM ns_attendant_group a " +
                "inner join ns_attendant_group_valid b on b.group_id=a.id " +
                "inner join ns_attendant_group_rel c on c.valid_id = b.id " +
                "WHERE company_id= ? " + ((hospitalId==null || hospitalId ==-1)? "": ("and a.hospital_id=" +hospitalId+" ")) +
                "and (b.effective_time <=? AND expire_time >= ?)";
        List groupRelDOS = extendDaoSupport.queryForList(sql, AttendantGroupRelDO.class, UserContext.getSeller().getCompanyId(),dateline, dateline);
        //转map key:护工id value:关联
        Map relDOMap = groupRelDOS.stream().collect(Collectors.toMap(AttendantGroupRelDO::getNursingId, a -> a, (a, b) -> a));

        //在组里的护工id
        List inGroup = data.stream().filter(vo -> {
            return relDOMap.containsKey(vo.getNursingId());
        }).map(WorkerDO::getNursingId).collect(Collectors.toList());

        String groupIds = inGroup.stream().map(relDOMap::get)
                .map(AttendantGroupRelDO::getGroupId).map(String::valueOf).collect(Collectors.joining(","));

        List inGroupServiceCount = this.getServiceCount(groupIds,true);

        //护工id
        String nursingIdStr = data.stream().map(WorkerDO::getNursingId).map(String::valueOf).collect(Collectors.joining(","));
        List serviceCount = this.getServiceCount(nursingIdStr, false);
        Map map=new HashMap<>();
        if(hospitalId==null || hospitalId== -1){
            List shops = memberDaoSupport.queryForList("select shop_id,shop_name from es_shop where company_id = ?", ShopDO.class, UserContext.getSeller().getCompanyId());
            map=shops.stream().collect(Collectors.toMap(ShopDO::getShopId, ShopDO::getShopName));
        }else{
            String hospitalName= memberDaoSupport.queryForString("select shop_name from es_shop where shop_id = ?",  hospitalId);
            map.put(hospitalId,hospitalName);
        }
        for (WorkerRecordVo vo : data) {
            if (!CollectionUtils.isEmpty(serviceCount)) {
                WorkerRecordVo workerRecordVo = serviceCount.stream().filter(serviceCountVO -> serviceCountVO.getWorkerId().equals(vo.getNursingId())).findFirst().orElse(null);
                vo.setServiceCount(workerRecordVo==null?0:workerRecordVo.getCount());
            } else {
                vo.setServiceCount(0);
            }
            AttendantGroupRelDO groupRelDO=null;
            //在组里,还要加上组当前在服务的服务数
            if (!CollectionUtils.isEmpty(relDOMap) && (groupRelDO=relDOMap.get(vo.getNursingId()))!=null) {
                AttendantGroupRelDO finalGroupRelDO = groupRelDO;
                WorkerRecordVo workerRecordVo = inGroupServiceCount.stream()
                        .filter(serviceCountVO -> serviceCountVO.getGroupId().equals(finalGroupRelDO.getGroupId()))
                        .findFirst().orElse(null);
                vo.setServiceCount(workerRecordVo==null?0:workerRecordVo.getCount());
            }
            String hospitalName=map.get(vo.getShopId())==null?"":map.get(vo.getShopId());
            vo.setHospitalName(hospitalName);
            // 护龄处理
            if (vo.getWorkingDate() != null) {
                vo.setWorkAge(DateUtil.getAge(vo.getWorkingDate()));
            }
        }

        return page;
    }

    @Override
    public void downloadWorkerZip(Integer hospitalId, String searchStr, Date entryDate, Integer serviceAge, Integer state, Integer sex, Integer photo) {
        Page page = this.workerRecordList(hospitalId, searchStr, entryDate, serviceAge, state, sex, photo, 0, 0);
        List data = page.getData(); //所有护工
        if(org.apache.commons.collections.CollectionUtils.isEmpty(data)){
            throw new ServiceException(ExtendedErrorCode.E201.code(),"无可导出数据");
        }
        String nursingIds = data.stream().map(WorkerDO::getNursingId).map(String::valueOf).collect(Collectors.joining(","));
        String sql="select id,attendant_id,cert_name,cert_type,acquisition_time,expire_time,pictures from ns_attendant_cert " +
                "where attendant_id in (" + nursingIds +") and is_delete =0";
        //所有护工的职业信息
         List allCertDOs = extendDaoSupport.queryForList(sql, AttendantCertDO.class);

        //所有护工的工作经历
        sql="select id,attendant_id,company_name,entry_date,leave_date,leave_reason,labels " +
                "from ns_attendant_work_history where attendant_id in (" + nursingIds +") and is_delete=0";
        List allWorkHistory = extendDaoSupport.queryForList(sql, AttendantWorkHistoryVO.class);

        data.forEach(vo->{
            if (!CollectionUtils.isEmpty(allCertDOs)) {
                List attendantCertDOs = allCertDOs.stream().filter(item -> item.getAttendantId().equals(vo.getNursingId())).collect(Collectors.toList());
                vo.setAttendantCertDOList(attendantCertDOs);
            }
            if (!CollectionUtils.isEmpty(allWorkHistory)) {
                List historyVOS = allWorkHistory.stream().filter(item -> item.getAttendantId().equals(vo.getNursingId())).collect(Collectors.toList());
                vo.setWorkHistoryVOList(historyVOS);
            }
        });

        this.exportWorkerZip(data);
    }
    private void exportWorkerZip(List data){
        HttpServletResponse response = ThreadContextHolder.getHttpResponse();
        String[] baseColumns = {"护工姓名", "护工编号",
                "所属医院", "手机号码",
                "身份证号", "民族",
                "性别", "出生日期",
                "籍贯", "户籍地址",
                "家庭地址", "星级","是否有保险",
                "文化程度", "婚姻状况",
                "语言能力", "入职日期",
                "紧急联系人", "紧急联系电话",
                "开户行名称", "开户行代码",
                "银行卡号", "账户类型",
                "开户证件类型", "账户名",
                "证件号","银行预留号码","体检时间","有效期"};
        List list = Arrays.asList(baseColumns);
        List columnNames = new ArrayList<>();
        columnNames.addAll(list);

         //护理证书最多的记录
        WorkerRecordVo certWorkerRecord = data.stream().filter(vo->vo.getAttendantCertDOList()!=null).max(Comparator.comparingInt(vo -> vo.getAttendantCertDOList().size())).orElse(null);
       if (!ObjectUtils.isEmpty(certWorkerRecord)) {
           List attendantCertDOList = certWorkerRecord.getAttendantCertDOList().stream().filter(vo->Integer.valueOf(0).equals(vo.getCertType())).collect(Collectors.toList());
           for (int i = 1; i <= attendantCertDOList.size(); i++) {
               columnNames.add("护理证书"+i);
               columnNames.add("获取时间"+i);
           }
       }

        //筛选出工作经历最多的护工
        WorkerRecordVo workerRecordVo = data.stream().filter(vo->vo.getWorkHistoryVOList()!=null).max(Comparator.comparingInt(vo -> vo.getWorkHistoryVOList().size())).orElse(null);
        if (!ObjectUtils.isEmpty(workerRecordVo)) {
            List workHistoryList = workerRecordVo.getWorkHistoryVOList();
            for (int i = 1; i <= workHistoryList.size(); i++) {
                columnNames.add("入职公司"+i);
                columnNames.add("入职时间"+i);
                columnNames.add("离职时间"+i);
                columnNames.add("离职原因"+i);
            }
        }

        String sheetName = "护工档案信息表";
        String[] headers = columnNames.toArray(new String[columnNames.size()]);
        // 创建excel工作簿
        HSSFWorkbook workBook = CreateWorkerSheetUtil.createWorkerSheet(headers, sheetName);
        //获取工作表sheet
        HSSFSheet sheet = workBook.getSheet(sheetName);
        //填充数据

        for (int i = 0; i < data.size(); i++) {
            WorkerRecordVo entity = data.get(i);
            HSSFRow nextRow = sheet.createRow(i + 2);
            Integer column = 0;
            nextRow.createCell(column++).setCellValue(entity.getName());
            nextRow.createCell(column++).setCellValue(entity.getEmployeeNumber());
            nextRow.createCell(column++).setCellValue(entity.getHospitalName());
            nextRow.createCell(column++).setCellValue(entity.getMobile());
            nextRow.createCell(column++).setCellValue(entity.getIdCardNumber());
            nextRow.createCell(column++).setCellValue(entity.getNation());
            nextRow.createCell(column++).setCellValue(entity.getSex()==null?"":entity.getSex()==1?"男":"女");
            nextRow.createCell(column++).setCellValue(entity.getBirthday()==null?"":DateUtil.toString(entity.getBirthday(),"yyyy-MM-dd"));
            nextRow.createCell(column++).setCellValue(entity.getNativePlace());// "籍贯
            nextRow.createCell(column++).setCellValue(entity.getPermanentAddress());//户籍地址
            nextRow.createCell(column++).setCellValue(entity.getResidentialAddress());//家庭地址
            nextRow.createCell(column++).setCellValue(entity.getStarLevel()==null?"":getStartLevel(entity.getStarLevel())); //星级 0:普通护工;4:四星护工;5:五星护工
            nextRow.createCell(column++).setCellValue(entity.getInsurance()==null?"":entity.getInsurance()==1?"有":"无");//是否有保险
            nextRow.createCell(column++).setCellValue(getEducation(entity.getEducation()==null?0:entity.getEducation()));//文化程度 0:无;1:小学,2:初中,3:高中,4:大学',
            nextRow.createCell(column++).setCellValue(entity.getMaritalStatus()==null?"":getMaritalStatus(entity.getMaritalStatus()));//婚姻状况 0:未婚 1:已婚 2:离异
            nextRow.createCell(column++).setCellValue(entity.getLanguageAbility());
            nextRow.createCell(column++).setCellValue(entity.getEntryDate()==null?"":DateUtil.toString(entity.getEntryDate(),"yyyy-MM-dd"));
            nextRow.createCell(column++).setCellValue(entity.getEmergencyContact());
            nextRow.createCell(column++).setCellValue(entity.getEmergencyPhone());
            nextRow.createCell(column++).setCellValue(entity.getBankName());//开户行名称
            nextRow.createCell(column++).setCellValue(entity.getBankCode());
            nextRow.createCell(column++).setCellValue(entity.getAccountNo());//银行卡号
            nextRow.createCell(column++).setCellValue(entity.getAccountType());//账户类型
            nextRow.createCell(column++).setCellValue(entity.getIdType());
            nextRow.createCell(column++).setCellValue(entity.getAccountName());//账户名
            nextRow.createCell(column++).setCellValue(entity.getLicenseNum());//证件号
            nextRow.createCell(column++).setCellValue(entity.getTelephone());//银行预留号码

            List entityCertDOList = entity.getAttendantCertDOList(); //所有职业信息
            if (!CollectionUtils.isEmpty(entityCertDOList)) {
                //健康证
                AttendantCertDO attendantCertDO = entityCertDOList.stream().filter(vo -> Integer.valueOf(1).equals(vo.getCertType())).findFirst().orElse(null);
                if (!ObjectUtils.isEmpty(attendantCertDO)) {
                    nextRow.createCell(column++).setCellValue(attendantCertDO.getAcquisitionTime()==null?"":DateUtil.toString(attendantCertDO.getAcquisitionTime(),"yyyy-MM-dd"));//体检时间(时间戳)
                    nextRow.createCell(column++).setCellValue(attendantCertDO.getExpireTime()==null?"":DateUtil.toString(attendantCertDO.getExpireTime(),"yyyy-MM-dd"));//有效期(时间戳)
                }

                //职业证书
                List certList = entityCertDOList.stream().filter(vo -> Integer.valueOf(0).equals(vo.getCertType())).collect(Collectors.toList());
                if (!CollectionUtils.isEmpty(certList)) {
                    for (AttendantCertDO certDO : certList) {
                        nextRow.createCell(column++).setCellValue(certDO.getCertName());//证书名
                        nextRow.createCell(column++).setCellValue(certDO.getAcquisitionTime()==null?"":DateUtil.toString(certDO.getAcquisitionTime(),"yyyy-MM-dd"));//有效期(时间戳)
                    }
                }
            }

            int maxCertSize = certWorkerRecord==null?0:certWorkerRecord.getAttendantCertDOList().size();
            int certSize = entityCertDOList == null ? 0 : entityCertDOList.size();
            int sub = maxCertSize * 2 - certSize * 2;
            column=column+sub;

            List workHistoryVOList = entity.getWorkHistoryVOList();//所有工作经历
            if (!CollectionUtils.isEmpty(workHistoryVOList)) {
                for (AttendantWorkHistoryVO historyVO : workHistoryVOList) {
                    nextRow.createCell(column++).setCellValue(historyVO.getCompanyName());//公司名
                    nextRow.createCell(column++).setCellValue(historyVO.getEntryDate()==null?"":DateUtil.toString(historyVO.getEntryDate(),"yyyy-MM-dd"));//入职(时间戳)
                    nextRow.createCell(column++).setCellValue(historyVO.getLeaveDate()==null?"":DateUtil.toString(historyVO.getLeaveDate(),"yyyy-MM-dd"));//离职
                    nextRow.createCell(column++).setCellValue(historyVO.getLeaveReason());//原因
                }
            }
        }

        Map workerPics = getWorkerPics(data);

        response.setContentType("application/octet-stream");
        response.setHeader("Access-Control-Expose-Headers", "downloadFileName, Content-Disposition");
        try {
            response.setHeader("downloadFileName", URLEncoder.encode("护工档案.zip", "UTF-8"));
            response.setHeader("Content-Disposition", "attachment;filename*=UTF-8''" + URLEncoder.encode("护工档案.zip", "UTF-8"));
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }

        try {
            // ServletOutputStream out = response.getOutputStream();
            // workBook.write(out);
            // out.close();
         /*   ZipOutputStream zos = new ZipOutputStream(response.getOutputStream());
            workerPics.forEach((key,value)->{
                for (int i = 0; i < value.length; i++) {
                    try {
                        URL url = new URL(value[i]);
                        zos.putNextEntry(new ZipEntry(key+i+".jpg"));
                        InputStream fis = url.openConnection().getInputStream();
                        byte[] buffer = new byte[1024];
                        int r = 0;
                        while ((r = fis.read(buffer)) != -1) {
                            zos.write(buffer, 0, r);
                        }
                        fis.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            });*/

            ZipOutputStream zos = new ZipOutputStream(response.getOutputStream());

            workerPics.forEach((key, value) -> {
                for (int i = 0; i < value.length; i++) {
                    InputStream inputStream = fileManager.downLoadFile(value[i]);//这是获取本地图片的输入流
                    if (null == inputStream) {
                        continue;
                    }
                    try {
                        // 打开输出流
                        // ZipOutputStream stream=null;
                        // 读取和写入信息
                        // ByteBuffer buff = ByteBuffer.allocate(1024);
                        zos.putNextEntry(new ZipEntry(key + "/" + i + ".jpg")); //这行代码是划分目录
                        byte[] buff = new byte[1024];
                        int r = 0;
                        while ((r = inputStream.read(buff)) != -1) {
                            zos.write(buff, 0, r);
                        }
                        inputStream.close();
                        // stream.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            });

            //将表格放入压缩包
            ByteArrayOutputStream os = new ByteArrayOutputStream();
            try {
                workBook.write(os);
            } catch (IOException e) {
                e.printStackTrace();
            }
            byte[] content = os.toByteArray();
            //写入输入流
            InputStream is = new ByteArrayInputStream(content);
            // 用于将数据压缩成Zip文件格式
            zos.putNextEntry(new ZipEntry("护工档案信息表.xls"));
            int bytesRead = 0;
            while ((bytesRead = is.read()) != -1) {
                zos.write(bytesRead);
            }
            zos.flush();
            zos.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
package com.enation.app.javashop.core.base.plugin.upload;

import java.io.*;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.util.*;
import java.util.zip.ZipOutputStream;

import com.enation.app.javashop.core.base.SettingGroup;
import com.enation.app.javashop.core.base.model.vo.RadioOption;
import com.enation.app.javashop.core.client.system.SettingClient;
import com.enation.app.javashop.core.goods.model.dto.GoodsSettingVO;
import com.enation.app.javashop.framework.util.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.enation.app.javashop.core.base.model.dto.FileDTO;
import com.enation.app.javashop.core.base.model.vo.ConfigItem;
import com.enation.app.javashop.core.base.model.vo.FileVO;
import com.enation.app.javashop.framework.context.ThreadContextHolder;

import javax.servlet.ServletContext;



/**
 * 本地上传插件
 *
 * @author zh
 * @version v7.0
 * @since v7.0
 * 2018年3月22日 下午7:40:27
 */
@SuppressWarnings("unchecked")
@Component
public class LocalPlugin implements Uploader {

    @Autowired
    ServletContext context;

    @Autowired
    private SettingClient settingClient;

    @Override
    public List definitionConfigItem() {
        List list = new ArrayList<>();
        ConfigItem nginxOpen = new ConfigItem();
        nginxOpen.setType("radio");
        nginxOpen.setName("nginx_open");
        nginxOpen.setText("nginx支持");
        List options = new ArrayList<>();
        RadioOption radioOption = new RadioOption();
        radioOption.setLabel("不支持");
        radioOption.setValue(0);
        options.add(radioOption);

        radioOption = new RadioOption();
        radioOption.setLabel("支持");
        radioOption.setValue(1);
        options.add(radioOption);
        nginxOpen.setOptions(options);


        ConfigItem resourceUrl = new ConfigItem();
        resourceUrl.setType("text");
        resourceUrl.setName("static_server_domain");
        resourceUrl.setText("域名");

        ConfigItem serviceUrl = new ConfigItem();
        serviceUrl.setType("text");
        serviceUrl.setName("static_server_path");
        serviceUrl.setText("路径");

        list.add(nginxOpen);
        list.add(resourceUrl);
        list.add(serviceUrl);
        return list;
    }

    @Override
    public String getPluginId() {
        return "localPlugin";
    }

    /**
     * 删除本地图片
     *
     * @param filePath 文件全路径
     */
    @Override
    public void deleteFile(String filePath, Map config) {
        filePath = filePath.replaceAll(AbstractRequestUtil.getDomain(), ThreadContextHolder.getHttpRequest().getServletContext().getRealPath(""));
        FileUtil.delete(filePath);
    }

    /**
     * 获取时间
     */
    private String getTimePath() {
        Calendar now = Calendar.getInstance();
        int year = now.get(Calendar.YEAR);
        int month = now.get(Calendar.MONTH) + 1;
        int date = now.get(Calendar.DAY_OF_MONTH);
        int minute = now.get(Calendar.HOUR_OF_DAY);
        String filePath = "";
        if (year != 0) {
            filePath += year + "/";
        }
        if (month != 0) {
            filePath += month + "/";
        }
        if (date != 0) {
            filePath += date + "/";
        }
        if (minute != 0) {
            filePath += minute + "/";
        }
        return filePath;
    }

    @Override
    public FileVO upload(FileDTO input, String scene, Map config) {
        //参数校验
        if (input.getStream() == null) {
            throw new IllegalArgumentException("file or filename object is null");
        }
        //获取文件名词
        String fileName = input.getName();
        //获取文件后缀
        String ext = input.getExt();
        //  拼接文件名
        fileName = DateUtil.toString(new Date(), "mmss") + StringUtil.getRandStr(4) + "." + ext;
        //  返回浏览器路径
        String path = (String) config.get("static_server_domain");
        path=path==null||path.equals("")?AbstractRequestUtil.getDomain():path;
        // 入库路径
        String filePath = (String) config.get("static_server_path");
        filePath=filePath==null||filePath.equals("")?context.getRealPath("/"):filePath;
        // 拼接路径
        path = path + "/statics/attachment/" + scene + "/";
        filePath = filePath + "statics/attachment/" + scene + "/";
        // 获取当前时间
        String timePath = this.getTimePath();
        // 拼接返回浏览器路径
        path += timePath + fileName;
        // 拼接入库路径及文件名 */
        filePath += timePath;
        filePath += fileName;
        //写入文件
        FileUtil.write(input.getStream(), filePath);
        String photoSizeSettingJson = settingClient.get(SettingGroup.GOODS);

        GoodsSettingVO photoSizeSetting = JsonUtil.jsonToObject(photoSizeSettingJson,GoodsSettingVO.class);
        PicUtil picUtil=null;
        try {
            picUtil=new PicUtil(filePath);

            picUtil.zoom(photoSizeSetting.getThumbnailWidth(),photoSizeSetting.getThumbnailHeight());
            picUtil.zoom(photoSizeSetting.getSmallWidth(),photoSizeSetting.getSmallHeight());
            picUtil.zoom(photoSizeSetting.getBigWidth(),photoSizeSetting.getBigHeight());
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            if (picUtil!=null) {
                picUtil.release();
            }
        }
        //  返回浏览器
        FileVO file = new FileVO();
        file.setName(fileName);
        file.setUrl(path);
        file.setExt(ext);
        return file;
    }

    /**
     * 生成缩略图全路径 本地存储缩略图格式为 原图片名称_宽x高.原图片名称后缀
     * 如原图路径为/User/2017/03/04/original.jpg,需要生成100x100的图片 则缩略图全路径为
     * /User/2017/03/04/original.jpg_100x100.jpg
     */
    @Override
    public String getThumbnailUrl(String url, Integer width, Integer height) {
        // 截图原图后缀
        String suffix = url.substring(url.lastIndexOf("."), url.length());
        // 缩略图全路径
        String thumbnailPah = url + "_" + width + "x" + height + suffix;
        // 返回缩略图全路径
        return thumbnailPah;

    }

    @Override
    public String getPluginName() {
        return "本地存储";
    }

    @Override
    public InputStream downLoadFile(String url, Map config) {
        String path = (String) config.get("static_server_domain");
        path=path==null||path.equals("")?AbstractRequestUtil.getDomain():path;
        // 入库路径
        String filePath = (String) config.get("static_server_path");
        filePath=filePath==null||filePath.equals("")?context.getRealPath("/"):filePath;
        String replace = url.replace(path+"/", filePath);
        File file = new File(replace);
        if (!file.exists()) {
            return null;
        }
        // 打开输入流
        try {
            FileInputStream reader = new FileInputStream(file);
            BufferedInputStream bufferedInputStream = new BufferedInputStream(reader);
            return bufferedInputStream;
        } catch (IOException e) {
            e.printStackTrace();
        }

        return null;
    }

    @Override
    public Integer getIsOpen() {
        return 1;
    }

}

你可能感兴趣的:(java)