美文网首页
java 压缩excel文件,并上传oss对象存储(不生成临时文

java 压缩excel文件,并上传oss对象存储(不生成临时文

作者: 秋风落叶黄 | 来源:发表于2020-08-17 14:24 被阅读0次

    最近在项目中需要把定时任务(不让产品找我导数据)中生成excel并上传oss,由于数据中有一些敏感信息,因此对文件进行加密。由于整个操作是在内存中进行的,因为不想生成临时文件来保存Excel文件。

maven依赖:

<dependency>
    <groupId>net.lingala.zip4j</groupId>
    <artifactId>zip4j</artifactId>
    <version>2.6.1</version>
</dependency>

一般情况下使用Java压缩文件方法:

ZipParameters zipParameters = new ZipParameters();
zipParameters.setEncryptFiles(true);
zipParameters.setEncryptionMethod(EncryptionMethod.AES);
// Below line is optional. AES 256 is used by default. You can override it to use AES 128. AES 192 is supported only for extracting.
zipParameters.setAesKeyStrength(AesKeyStrength.KEY_STRENGTH_256); 

List<File> filesToAdd = Arrays.asList(
    new File("somefile"), 
    new File("someotherfile")
);

ZipFile zipFile = new ZipFile("filename.zip", "password".toCharArray());
zipFile.addFiles(filesToAdd, zipParameters);

该方式最终会生成一个临时文件,下面介绍下不生成文件方式

                ByteArrayOutputStream bos = new ByteArrayOutputStream();//存储excel流
                XSSFWorkbook workbook = new XSSFWorkbook();
                //TODO excel操作
             
                workbook.write(bos);
                workbook.close();

                String fileName = "filename"
                ZipParameters zipParameters = new ZipParameters();
                zipParameters.setEncryptFiles(true);
                zipParameters.setEncryptionMethod(EncryptionMethod.AES);//采用AES对称加密
                zipParameters.setAesKeyStrength(AesKeyStrength.KEY_STRENGTH_256);
                zipParameters.setFileNameInZip(fileName + ".xlsx"); //设置放在压缩包里的文件名

                ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
                try (ZipOutputStream zos = new ZipOutputStream(outputStream, "password".toCharArray())) {
                    zos.putNextEntry(zipParameters);
                    bos.writeTo(zos);
                    zos.closeEntry();
                }
                ossUtil.upload(fileName + ".zip", outputStream.toByteArray()); //上传oss对象存储

OssUtil:


    public String upload(String fileName, byte[] content) {
        log.info("上传文件到oss: fileName={} contentLength={}", fileName, content.length);
        try (InputStream inputStream = new ByteArrayInputStream(content)) {
            ObjectMetadata objectMetadata = new ObjectMetadata();
            objectMetadata.setContentLength(content.length);
            s3.putObject(config.getBucketName(), fileName, inputStream, objectMetadata);
            return config.domain + fileName;
        } catch (Exception e) {
            log.error("上传文件失败:", e);
            throw new BusinessException(BusinessExceptionEnum.SERVER_INTERNAL_ERROR);
        }
    }

相关文章

网友评论

      本文标题:java 压缩excel文件,并上传oss对象存储(不生成临时文

      本文链接:https://www.haomeiwen.com/subject/ywhqjktx.html