我的表单内有好几个文件上传控件,每个控件里有多个文件。在后台用了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位是可以的,但是我不想中间有这么一步或者大家有什么别的方式可以解决?

解决方案 »

  1.   

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

  2.   

    Quote: 引用 1 楼 qybao 的回复:
    试了一下还是一样的错。。就算不给他加密,直接byte写出来也不行。。
      

  3.   

    不要直接生成文件,用zip流读取试试 
     byte[] buffer = new BASE64Decoder().decodeBuffer(base64Code);
    ZipInputStream zs = new ZipInputStream(new ByteArrayInputStream(buffer));
    zs.getNextEntry();
    ...