how to zipping multiple files and encode to base64?

Tags: ,



I have made a few lines of code and worked for a while, the program I created is like this. When I compress the .zip format, an example.zip file will be formed in the directory. The next step the program runs the command to look for the .zip filename in the directory. If found it will be converted into base64 and sent as a response body.

My question is, how do I process the .zip format? This program does not form files in the directory, but immediately converts to the base64 stage, so there is no need for an example.zip file in the directory.

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

Answer

Controller class :

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

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

}


Source: stackoverflow