首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >如何压缩多个文件并编码为base64?

如何压缩多个文件并编码为base64?
EN

Stack Overflow用户
提问于 2019-06-13 12:17:10
回答 1查看 384关注 0票数 1

我写了几行代码,工作了一段时间,我创建的程序是这样的。当我压缩.zip格式时,会在目录中形成一个example.zip文件。下一步,程序运行命令在目录中查找.zip文件名。如果找到,它将被转换为base64并作为响应体发送。

我的问题是,如何处理.zip格式?此程序不会在目录中形成文件,但会立即转换为base64 stage,因此目录中不需要example.zip文件。

代码语言:javascript
运行
复制
@Autowired
private FileConvert fileConvert;

@GetMapping("/{formCode}/getZip")
public ResponseEntity<JSONObject> getZipDocument(@PathVariable(value="formCode") String formCode) throws IOException{
        try {
            List<DocumentImportan> docList = docService.getSelectedFormCode(formCode);
            List<Object> listDoc = new ArrayList<>();
            HashMap<String, Object> data = new HashMap<>();
            String[] dataPdf = new String[docList.size()];
            String nameFile = null;
            int no = 0;
            for(DocumentImportan document : docList) {
                String[] arrCode = document.getFormCode().split(",");
                String[] arrDesc = document.getFormDesc().split(",");
                for(int i = 0; i < arrCode.length; i++) {
                    if (arrCode[i].equals(formCode)) {
                        nameFile = arrDesc[i];
                    }
                }
                dataPdf[no] = document.getPdfName();

                no++;
            }

**//process the .zip format method**
            String files = fileConvert.zip(dataPdf, nameFile);

**//base64 convert process**
            String base64Zip = fileConvert.encodeFile(files);
            data.put("zipBase64", base64Zip);
            listDoc.add(data);
            fileConvert.deleteFileExist(files);

            jsonResponse.put(CONST_MSG, "Zip Successful Load");
            jsonResponse.put(CONST_STATUS, 200);
            jsonResponse.put("data", listDoc);

        } catch (Exception e) {
            logger.info(String.format(CONST_ERRORMSG, e.getMessage()));
            jsonResponse.put(CONST_MSG, e.getMessage());
        }
        return new ResponseEntity<>(jsonResponse, HttpStatus.OK);
    }

FileConvert.class

代码语言:javascript
运行
复制
**//method format .zip**
public String zip(String[] data, String nameFile) {
        long timeStamp = new Date().getTime();
        String zipFile = timeStamp+"_"+nameFile+".zip";
        String[] srcFiles = data;

        try {
            byte[] buffer = new byte[1024];
            FileOutputStream fos = new FileOutputStream(context.getEnvironment().getProperty(CONST_FOLDER) + File.separatorChar + zipFile);
            ZipOutputStream zos = new ZipOutputStream(fos);

            for (int i=0; i < srcFiles.length; i++) {
                File srcFile = new File(context.getEnvironment().getProperty(CONST_FOLDER) + File.separatorChar + srcFiles[i]);
                FileInputStream fis = new FileInputStream(srcFile);
                zos.putNextEntry(new ZipEntry(srcFile.getName()));
                int length;
                while ((length = fis.read(buffer)) > 0) {
                    zos.write(buffer, 0, length);
                }
                zos.closeEntry();
                fis.close();
            }
            zos.close();
        }
        catch (IOException e) {
            logger.error(String.format("Decode file error caused ", e.getMessage()));
        }
        return zipFile;
    }




**//method convert base64**
public String encodeFile(String path) throws IOException {
        File file = new File(context.getEnvironment().getProperty(CONST_FOLDER) + File.separatorChar + path);
        InputStream is = new FileInputStream(file);
        long length = file.length();
        byte[] gambar = new byte[(int) length];
        int readGambar = is.read(gambar);
        if (readGambar > 0) {
            byte[] bytes = Base64.encodeBase64(gambar);
            is.close();
            return new String(bytes);
        } else {
            return null;
        }
    }
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2020-11-20 12:00:11

控制器类:

代码语言:javascript
运行
复制
@Autowired
private FileConvert fileConvert;

@GetMapping("/{formCode}/getZip")
public ResponseEntity<JSONObject> getZipDocument(@PathVariable(value = "formCode") String formCode) throws IOException{
        try {
            List<DocumentImportan> docList = docService.getSelectedFormCode(formCode);
            List<Object> listDoc = new ArrayList<>();
            HashMap<String, Object> data = new HashMap<>();
            String[] dataPdf = new String[docList.size()];
            int no = 0;
            if (docList.size() > 0) {
                for(DocumentImportan document : docList) {
                    dataPdf[no] = document.getPdfName();
                    no++;
                }
                String files = fileConvert.zip(dataPdf);
                data.put("zipBase64", files);
            }else {
                data.put("zipBase64", null);
            }
            listDoc.add(data);
            
            jsonResponse.put(CONST_MSG, "Zip Successful Load");
            jsonResponse.put(CONST_STATUS, 200);
            jsonResponse.put("data", listDoc);
        } catch (Exception e) {
            logger.info(String.format(CONST_ERRORMSG, e.getMessage()));
            jsonResponse.put(CONST_MSG, e.getMessage());
        }
        return new ResponseEntity<>(jsonResponse, HttpStatus.OK);
    }

FileConvert类:

代码语言:javascript
运行
复制
@Service
public class FileConvert {

    private static final String CONST_FOLDER = "image.path";
    private static final Logger logger = LoggerFactory.getLogger(FileConvert.class);

    @Autowired
    private ApplicationContext context;

    public String zip(String[] data) throws IOException{
        String[] srcFiles = data;
        String encodedBase64 = null;

        byte[] buffer = new byte[1024];
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        ZipOutputStream zos = new ZipOutputStream(baos);
        try {
            for (int i=0; i < srcFiles.length; i++) {
                File srcFile = new File(context.getEnvironment().getProperty(CONST_FOLDER) + File.separatorChar + srcFiles[i]);
                try(FileInputStream fis = new FileInputStream(srcFile)){
                    zos.putNextEntry(new ZipEntry(srcFile.getName()));
                    int length;
                    while ((length = fis.read(buffer)) > 0) {
                        zos.write(buffer, 0, length);
                    }
                    zos.closeEntry();
                }
            }
            zos.close();
        }
        catch (IOException e) {
            logger.error("Decode file error caused ");
            logger.error(e.getMessage());
        }
        finally {
            zos.close();
        }
        byte[] bytes = baos.toByteArray();
        encodedBase64 = new String(Base64.encodeBase64(bytes));
        return encodedBase64;
    }

}
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/56573297

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档