java导入导出压缩包

java导入导出压缩包

最近有个需求,需要将导入导出压缩包格式的JSON文件,然后存入数据库中,特整理如下:

一:首先是导出压缩包

1.首先是controller

  /**
     * 接口必填配置导出
     *
     * @author 
     * @email
     * @date 2023/2/27 9:43
     */
    @PostMapping("exportVchVerchurConfig")
    public void exportVchVerchurConfig(@RequestBody VchVerchurConfig vchVerchurConfig, HttpServletResponse response) {
        log.info("导出|用户:{},入参:{}", securityUtil.getUserCode(), JsonUtil.toJson(vchVerchurConfig));
        try {
            vchVerchurConfigService.exportVchVerchurConfig(vchVerchurConfig, response);
        } catch (Exception e) {
            log.error("导出失败,入参:{}", JsonUtil.toJson(vchVerchurConfig), e);
        }
        log.info("用户:{},导出成功", securityUtil.getUserCode());
    }

2.然后是service具体内容

/**
	 * 接口必填配置导出
	 *
	 * @author 
	 * @email
	 * @date 2023/2/27 9:53
	 */
	@Override
	public void exportVchVerchurConfig(VchVerchurConfig vchVerchurConfig, HttpServletResponse response) throws Exception {
	//以下是从数据库中获取需要导出的内容
		VchVerchurConfigCondition vchVerchurConfigCondition = new VchVerchurConfigCondition();
		BeanUtils.copyProperties(vchVerchurConfig, vchVerchurConfigCondition);
		List<VchVerchurConfig> vchVerchurConfig1 = vchVerchurConfigManager.findVchVerchurConfigList(vchVerchurConfigCondition);

//导出具体逻辑
		OutputStream outputStream = null;
		try {
			ByteArrayOutputStream baos = new ByteArrayOutputStream();
			try (ZipOutputStream zip = new ZipOutputStream(baos)) {
			    //这个是压缩包里面的包名
				ZipEntry entry = new ZipEntry(vchVerchurConfig1.get(0).getSourceOrderTypeCode() + "." + CommonCst.CHURCONFIGFILE_SUFFIX);
				
				zip.putNextEntry(entry);
                //序列化导出内容				
				zip.write(JSONObject.toJSONString(vchVerchurConfig1).getBytes());
				zip.closeEntry();
			}
			byte[] bytes = baos.toByteArray();
			//base64加密信息可以不用
		//	bytes = EncryptUtil.encrypt(bytes);


			response.setContentType("application/octet-stream;charset=utf-8");
			//设置压缩包最外面一层的名字
			response.setHeader("Content-Disposition", "attachment; filename=" + String.format("vchVerchurConfig_%s.zip", vchVerchurConfig.getSourceOrderTypeCode()));
			outputStream = response.getOutputStream();
			outputStream.write(bytes);
			outputStream.flush();
		} catch (Exception e) {
			log.error("导出规则失败", e);
			throw e;
		} finally {
			IOUtils.closeQuietly(outputStream);
		}
	}
	

以下是导出测试:
首先是接口
在这里插入图片描述

然后是导出结果
在这里插入图片描述

二:然后是导入压缩包

1.首先是controller没啥说的

  /**
     * 接口必填配置导入
     *
     * @author 
     * @email
     * @date 2023/2/27 9:43
     */
    @PostMapping("importVchVerchurConfig")
    public HttpResult importVchVerchurConfig(@RequestBody MultipartFile file) {
        try {
            vchVerchurConfigService.importVchVerchurConfig(file);
        } catch (Exception e) {
            log.error("导入失败,入参:{}", e);
            return HttpResult.asResponse(WebErrorCode.RESULT_ERROR.getCode(), String.format("导入失败,原因:%s", e.getMessage()));
        }
        return HttpResult.successResponse("导入成功");
    }

2.然后是service

/**
	 * 接口必填配置导入
	 *
	 * @author 
	 * @email
	 * @date 2023/2/27 9:53
	 */
	@Override
	public HttpResult importVchVerchurConfig(MultipartFile file) throws Exception {
		if (file == null) {
			throw new BadRequestException("导入文件为空!");
		}
		ZipInputStream zis = null;
		try {
//			byte[] bytes = EncryptUtil.decrypt(file.getBytes());
			byte[] bytes = file.getBytes();
			zis = new ZipInputStream(new ByteArrayInputStream(bytes));
			ZipEntry zipEntry;
			while ((zipEntry = zis.getNextEntry()) != null) {
				if (zipEntry.isDirectory()) {
					continue;
				}
				String entryName = zipEntry.getName();
				//只能导入上面导出得文件类型
				if (org.apache.commons.lang3.StringUtils.isNotBlank(entryName) && entryName.endsWith(CommonCst.CHURCONFIGFILE_SUFFIX)) {
					List<String> contents = IOUtils.readLines(zis);
					if (!org.springframework.util.CollectionUtils.isEmpty(contents)) {
						for (String str : contents) {
							//反序列化内容
							List<VchVerchurConfig> vchVerchurConfigList = JSONObject.parseArray(str, VchVerchurConfig.class);
							VchVerchurConfigCondition vchVerchurConfigCondition = new VchVerchurConfigCondition();
				//以下是具体业务,把压缩包里的json内容存到数据库中
							vchVerchurConfigCondition.setSourceOrderTypeCode(vchVerchurConfigList.get(0).getSourceOrderTypeCode());
							vchVerchurConfigCondition.setIsDelete("0");
							List<VchVerchurConfig> vchVerchurConfigs = vchVerchurConfigManager.findVchVerchurConfigList(vchVerchurConfigCondition);
							if (CollectionUtils.isNotEmpty(vchVerchurConfigs)) {
								vchVerchurConfigManager.deleteVchVerchurConfigByCode(vchVerchurConfigCondition);
								vchVerchurConfigManager.insertVchVerchurConfigList(vchVerchurConfigList);
							} else {
								vchVerchurConfigManager.insertVchVerchurConfigList(vchVerchurConfigList);
							}
						}
					}
				}
			}
		} catch (Exception e) {
			log.error("导入失败", e);
			throw e;
		}
		return HttpResult.successResponse("导入成功");
	}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值