如何将多个文件压缩为.zip格式,然后将.zip格式转换为base64以用作响应?

时间:2019-06-13 04:17:09

标签: java spring-boot

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

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

@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

**//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;
        }
    }

1 个答案:

答案 0 :(得分:0)

控制器类:

@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类:

@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;
    }

}