whycxzp
2021-03-13 dbd5cf4f85c99c7c2189905d4972e42d0b2cbbe1
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
package com.whyc.util;
 
import org.apache.tomcat.util.codec.binary.Base64;
 
import java.io.*;
 
public class FileCopyUtil {
    /**
     * base64转File
     * @param base64
     * @param dest
     */
    public static boolean base64ToFile(String base64, File dest) {
        BufferedInputStream bis = null;
        BufferedOutputStream bos = null;
        try {
            //由于base64在传输过程中,+和/和=会被替换所以在解码前需要将base64还原成可用的base64
            base64 = base64.replaceAll(" ","+");
            base64 = base64.replaceAll("%2F","/");
            base64 = base64.replaceAll("%3D","=");
            //当使用springMVC时无需使用以上方法进行还原
 
            byte[] bytes = Base64.decodeBase64(base64.replace("\r\n", ""));
            bis = new BufferedInputStream(new ByteArrayInputStream(bytes));
            bos = new BufferedOutputStream(new FileOutputStream(dest));
            byte[] bts = new byte[1024];
            int len = -1;
            while((len = bis.read(bts)) != -1) {
                bos.write(bts,0,len);
            }
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        } finally {
            if (bos != null) {
                try {
                    bos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (bis != null) {
                try {
                    bis.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}