Java 如何压缩多个文件并编码到base64?
我已经编写了几行代码并工作了一段时间,我创建的程序是这样的。 压缩.zip格式时,目录中将形成一个example.zip文件。 下一步,程序运行命令在目录中查找.zip文件名。如果找到,它将转换为base64并作为响应主体发送 我的问题是,如何处理.zip格式?此程序不会在目录中形成文件,但会立即转换为base64阶段,因此目录中不需要example.zip文件Java 如何压缩多个文件并编码到base64?,java,spring-boot,Java,Spring Boot,我已经编写了几行代码并工作了一段时间,我创建的程序是这样的。 压缩.zip格式时,目录中将形成一个example.zip文件。 下一步,程序运行命令在目录中查找.zip文件名。如果找到,它将转换为base64并作为响应主体发送 我的问题是,如何处理.zip格式?此程序不会在目录中形成文件,但会立即转换为base64阶段,因此目录中不需要example.zip文件 @Autowired private FileConvert fileConvert; @GetMapping("/{formCod
@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);
}
@Autowired
私有文件转换文件转换;
@GetMapping(“/{formCode}/getZip”)
public ResponseEntity getZipDocument(@PathVariable(value=“formCode”)字符串formCode)引发IOException{
试一试{
List docList=docService.getSelectedFormCode(formCode);
List listDoc=new ArrayList();
HashMap数据=新的HashMap();
String[]dataPdf=新字符串[docList.size()];
字符串nameFile=null;
int no=0;
对于(文档导入文档:文档列表){
字符串[]arrCode=document.getFormCode().split(“,”);
字符串[]arrDesc=document.getFormDesc().split(“,”);
for(int i=0;i
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;
}
}
**//method format.zip**
公共字符串zip(字符串[]数据,字符串名称文件){
长时间戳=新日期().getTime();
字符串zipFile=timeStamp+“”+nameFile+“.zip”;
字符串[]srcFiles=数据;
试一试{
字节[]缓冲区=新字节[1024];
FileOutputStream fos=新的FileOutputStream(context.getEnvironment().getProperty(CONST_FOLDER)+File.separatorChar+zipFile);
ZipoutStream zos=新ZipoutStream(fos);
对于(int i=0;i0){
写入(缓冲区,0,长度);
}
zos.closeEntry();
fis.close();
}
zos.close();
}
捕获(IOE异常){
logger.error(String.format(“导致解码文件错误”,e.getMessage());
}
返回zipFile;
}
**//方法转换base64**
公共字符串编码文件(字符串路径)引发IOException{
File File=新文件(context.getEnvironment().getProperty(CONST_FOLDER)+File.separatorChar+path);
InputStream is=新文件InputStream(文件);
long length=file.length();
字节[]gambar=新字节[(int)长度];
int readGambar=is.read(gambar);
如果(readGambar>0){
byte[]bytes=Base64.encodeBase64(gambar);
is.close();
返回新字符串(字节);
}否则{
返回null;
}
}
控制器等级:
@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);
}
@Autowired
私有文件转换文件转换;
@GetMapping(“/{formCode}/getZip”)
public ResponseEntity getZipDocument(@PathVariable(value=“formCode”)字符串formCode)引发IOException{
试一试{
List docList=docService.getSelectedFormCode(formCode);
List listDoc=new ArrayList();
HashMap数据=新的HashMap();
String[]dataPdf=新字符串[docList.size()];
int no=0;
如果(docList.size()>0){
对于(文档导入文档:文档列表){
dataPdf[no]=document.getPdfName();
否++;
}
String files=fileConvert.zip(dataPdf);
data.put(“zipBase64”,文件);
}否则{
data.put(“zipBase64”,空);
}
listDoc.add(数据);
jsonResponse.put(CONST_MSG,“Zip成功加载”);
jsonResponse.put(CONST_STATUS,200);
jsonResponse.put(“数据”,listDoc);
}捕获(例外e){
logger.info(String.format(CONST_ERRORMSG,e.getMessage());
jsonResponse.put(CONST_MSG,e.getMessage());
}
返回新的ResponseEntity(jsonResponse,HttpStatus.OK);
}
文件转换类:
@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;
}
}
@服务
公共类文件转换{
私有静态最终字符串CONST_FOLDER=“image.path”;
私有静态最终记录器Logger=LoggerFactory.getLogger(FileConvert.class);
@自动连线
私有应用程序上下文上下文;
公共字符串zip(字符串[]数据)引发IOException{
字符串[]srcFiles=数据;
字符串encodedBase64=null;
字节[]缓冲区=新字节[1024];
ByteArrayOutputStream bas=新的ByteArrayOutputStream();
ZipOutputStream zos=新ZipOutputStream(BAS);