1. 程式人生 > 其它 >【HZERO】檔案服務

【HZERO】檔案服務

檔案服務

獲取檔案轉化為位元組流並上傳檔案伺服器

程式碼示例

@ApiOperation(value = "生成合同文件流")
    @Permission(level = ResourceLevel.ORGANIZATION)
    @ProcessLovValue(targetField = BaseConstants.FIELD_BODY)
    @PostMapping("/streamContract")
    public void streamContract(
            @RequestParam(value = "contractNum") String contractNum, @RequestParam(required = false) Long orderId, @PathVariable Long organizationId) {
        this.contractService.streamContract(contractNum, orderId, organizationId);
    }
 /**
     * 生成合同並上傳檔案伺服器
     * @param contractNum
     * @param orderId
     * @return
     */
    void streamContract(String contractNum, Long orderId, Long organizationId);
   @Override
    public void streamContract(String contractNum, Long orderId, Long organizationId) {
        try {
            //生成對賬資訊pdf檔案
            Map<String, String> reportMap = new HashMap(2);
            reportMap.put("contractNum", String.valueOf(contractNum));
            String reportCode = "";
            reportMap.put("orderId", String.valueOf(orderId));
            Contract tempContract = new Contract();
            tempContract.setContractNum(contractNum);
            Contract contract = contractService.selectOne(tempContract);
            String contractType = contract.getContractType();
            switch (contractType) {
                case("FREIGHTER"):
                    contractType = "CONTRACT_FREIGHTER";
                    break;
                case("SHIPPER_SINGLE"):
                    contractType = "CONTRACT_SHIPPER_SINGLE";
                    break;
                case("FREIGHTER_SINGLE"):
                    contractType = "CONTRACT_FREIGHTER_SINGLE";
                    break;
                case("ENTRUSTED_COLLECTION_AGREEMENT"):
                    contractType = "CONTRACT_ENTRUSTED_COLLECTION_AGREEMENT";
                    break;
                default:
            }
            reportMap.put("f-templateCode", contractType);
            reportCode = "HTMS.CONTRACT_FORM_PLATFORM";
            this.pdfPrintReportService.getPdfReport(organizationId, reportCode, "PDF", reportMap, true);
        } catch (Exception e) {
            throw new CommonException(e);
        }
    }
}
/**
     * @Author: 張繼釗
     * @Date: 2022/5/18
     * @Description: 獲取pdf檔案位元組流
     */
    public void getPdfReport(Long tenantId, String reportCode, String outputType, Map<String, String> reportParams, boolean isRowSpan) throws IOException;
 @Override
    public void getPdfReport(Long tenantId, String reportCode, String outputType, Map<String, String> reportParams, boolean isRowSpan) throws IOException {
        Map<String, String> routeParams = new HashMap(2);
        String reportUuid = null;
        String templateCode = reportParams.get("f-templateCode");
        reportUuid = commonService.queryReportUuid(reportCode, templateCode, tenantId);
        routeParams.put("reportUuid", reportUuid);
        routeParams.put("outputType", outputType);
        if (org.apache.commons.collections4.MapUtils.isEmpty((Map) reportParams)) {
            reportParams = new HashMap();
        }
 reportParams.replace("f-templateCode", templateCode);
        reportParams.put("f-lang", "zh_CN");

        String contractNum = reportParams.get("contractNum");
        String id = reportParams.get("orderId");
        //若不是單次承運、託運合同,查詢條件不需要運單id,設定預設值
        Long orderId = null;
        if (!"null".equals(id)) {
            orderId = Long.valueOf(id);
        }
        //獲取檔案後生成位元組流並上傳
        Response response = this.newIReportRemoteService.exportReportFile(tenantId, reportUuid, outputType, "zh_CN", templateCode, contractNum, orderId);
        Response.Body body = response.body();
        InputStream inputStream = body.asInputStream();
        String uuid = java.util.UUID.randomUUID().toString().replaceAll("-", "");
        try {
            try {
                ByteArrayOutputStream baos = new ByteArrayOutputStream();
                byte[] buffer = new byte[1024];
                int num = inputStream.read(buffer);
                while (num != -1) {
                    baos.write(buffer, 0, num);
                    num = inputStream.read(buffer);
                }
                baos.flush();
                Contract tempContract = new Contract();
                tempContract.setContractNum(contractNum);
                Contract contract = contractService.selectOne(tempContract);
                String fileName = contract.getName();
                this.uploadAttachment(tenantId, uuid, baos.toByteArray(), fileName);
                contract.setContractFile(uuid);
                contractService.updateByPrimaryKeySelective(contract);
            } finally {
                if (inputStream != null) {
                    inputStream.close();
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            throw new CommonException("推送單一視窗失敗: 檔案上傳失敗");
        }
}
 private void uploadAttachment(Long tenantId, String uuid, byte[] file, String fileName) {
        try {
            String fileUrl = this.fileClient.uploadAttachment(tenantId, "htms", "contract/", uuid, fileName + ".pdf", "application/pdf", "ALI", file);
            if (fileUrl.startsWith("{\"failed\":true")) {
                throw new CommonException(fileUrl);
            }
        } catch (Exception e) {
            e.printStackTrace();
            throw new CommonException(e.getMessage());
        }
    }
 public String uploadAttachment(Long organizationId, String bucketName, String directory, String attachmentUUID, String fileName, String fileType, String storageCode, byte[] byteFile) {
        return this.properties.isAutoMultipart() && this.shouldSlice(byteFile) ? this.uploadFileSlice(organizationId, bucketName, directory, storageCode, fileName, fileType, (String)null, byteFile) : (String)ResponseUtils.getResponse(this.fileRemoteService.uploadAttachByteFile(organizationId, bucketName, directory, fileName, attachmentUUID, fileType, storageCode, byteFile), String.class);
    }

核心程式碼

//獲取檔案後生成位元組流並上傳
        Response response = this.newIReportRemoteService.exportReportFile(tenantId, reportUuid, outputType, "zh_CN", templateCode, contractNum, orderId);
        Response.Body body = response.body();
        InputStream inputStream = body.asInputStream();
        String uuid = java.util.UUID.randomUUID().toString().replaceAll("-", "");
        try {
            try {
                ByteArrayOutputStream baos = new ByteArrayOutputStream();
                byte[] buffer = new byte[1024];
                int num = inputStream.read(buffer);
                while (num != -1) {
                    baos.write(buffer, 0, num);
                    num = inputStream.read(buffer);
                }
                baos.flush();
                Contract tempContract = new Contract();
                tempContract.setContractNum(contractNum);
                Contract contract = contractService.selectOne(tempContract);
                String fileName = contract.getName();
                this.uploadAttachment(tenantId, uuid, baos.toByteArray(), fileName);
                contract.setContractFile(uuid);
                contractService.updateByPrimaryKeySelective(contract);
            } finally {
                if (inputStream != null) {
                    inputStream.close();
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            throw new CommonException("推送單一視窗失敗: 檔案上傳失敗");
        }