FileUtils.java
2.41 KB
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
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
package com.erry.iclear.dateInterface.util;
import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;
import java.io.*;
/**
* 文件处理工具类
* mt
* 2023年6月7日10:25:04
*/
public class FileUtils {
/**
* 本地文件(图片、excel等)转换成Base64字符串
* @param imgPath
* @return
* @throws Exception
*/
public static String convertFileToBase64(String imgPath) throws Exception{
byte[] data = null;
InputStream in = null;
// 读取图片字节数组
try {
in = new FileInputStream(imgPath);
data = new byte[in.available()];
in.read(data);
} catch (IOException e) {
e.printStackTrace();
}finally {
if(in != null){
in.close();
}
}
// 对字节数组进行Base64编码,得到Base64编码的字符串
BASE64Encoder encoder = new BASE64Encoder();
String base64Str = encoder.encode(data);
return base64Str;
}
/**
* 将base64字符串,生成文件
* @param fileBase64String
* @param filePath
* @param fileName
* @return
*/
public static File convertBase64ToFile(String fileBase64String, String filePath, String fileName) {
BufferedOutputStream bos = null;
FileOutputStream fos = null;
File file = null;
try {
File dir = new File(filePath);
if (!dir.exists() && dir.isDirectory()) {//判断文件目录是否存在
dir.mkdirs();
}
BASE64Decoder decoder = new BASE64Decoder();
byte[] bfile = decoder.decodeBuffer(fileBase64String);
file = new File(filePath + File.separator + fileName);
fos = new FileOutputStream(file);
bos = new BufferedOutputStream(fos);
bos.write(bfile);
return file;
} catch (Exception e) {
e.printStackTrace();
return null;
} finally {
if (bos != null) {
try {
bos.close();
} catch (IOException e1) {
e1.printStackTrace();
}
}
if (fos != null) {
try {
fos.close();
} catch (IOException e1) {
e1.printStackTrace();
}
}
}
}
}