求助各位,如何在生成zip文件的时候,得到该文件的base64位的字符串

weixin_38587449 2019-02-03 04:59:18
我的表单内有好几个文件上传控件,每个控件里有多个文件。在后台用了MultipartFile 接受后 我想把每个框的文件压缩成一个zip,并且直接生成base64位的zip字符串,因为我需要在webservice中传输,目前的情况是生成文件没有问题,但是在转base64位时好像会破坏这个压缩文件,导致解码后打不开。如果先生成一个文件,再通过文件流的形式转base64位是没有问题的。我想问下这个有办法解决吗?


代码部分:
/**
 文件压缩zip
*/
public static String ZipFiles(MultipartFile[] srcfile,HttpServletRequest request) {
byte[] buf = new byte[1024];
ZipOutputStream out = null;
String compressedStr = null;
ByteArrayOutputStream bout = null;
try {
bout= new ByteArrayOutputStream();
out = new ZipOutputStream(bout);
for (int i = 0; i < srcfile.length; i++) {
System.out.print(srcfile[i].getOriginalFilename());
InputStream in = srcfile[i].getInputStream();
System.out.print(in);
out.putNextEntry(new ZipEntry(srcfile[i].getOriginalFilename()));
int len;
while ((len = in.read(buf)) > 0) {
out.write(buf, 0, len);
}
in.close();
out.closeEntry();


}
byte[] compressed = bout.toByteArray();
compressedStr = encoder.encodeBuffer(compressed);
out.close();
bout.close();


} catch (IOException e) {
e.printStackTrace();
} finally {
try {
out.close();
} catch (Exception e) {
e.printStackTrace();
}
}

return compressedStr;
}

public static void decoderBase64File(String base64Code)
throws Exception {
byte[] buffer = new BASE64Decoder().decodeBuffer(base64Code);
FileOutputStream out = new FileOutputStream("d://copytest.zip");
out.write(buffer);
out.close();

}
这样生成的文件缺失报 不可预料的压缩文件末端。。。。。如果先生成一个文件再用文件流的方式生成base64位是可以的,但是我不想中间有这么一步。。。或者大家有什么别的方式可以解决?

...全文
1251 3 打赏 收藏 转发到动态 举报
AI 作业
写回复
用AI写文章
3 条回复
切换为时间正序
请发表友善的回复…
发表回复
qybao 2019-02-12
  • 打赏
  • 举报
回复
不要直接生成文件,用zip流读取试试
byte[] buffer = new BASE64Decoder().decodeBuffer(base64Code);
ZipInputStream zs = new ZipInputStream(new ByteArrayInputStream(buffer));
zs.getNextEntry();
...


weixin_38587449 2019-02-11
  • 打赏
  • 举报
回复
[quote=引用 1 楼 qybao 的回复:]试了一下还是一样的错。。。。。就算不给他加密,直接byte写出来也不行。。
qybao 2019-02-04
  • 打赏
  • 举报
回复
have a try

compressedStr = bout.toString();
or
byte[] compressed = bout.toByteArray();
compressedStr = new Base64Encoder().encodeToString(compressed);

81,122

社区成员

发帖
与我相关
我的任务
社区描述
Java Web 开发
社区管理员
  • Web 开发社区
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧