1 import java.io.ByteArrayOutputStream;
2 import java.io.File;
3 import java.io.FileOutputStream;
4 import java.io.InputStream;
5 import java.io.OutputStream;
6 import org.apache.commons.codec.binary.Base64;
7
8 /**
9 * 将图片保存到项目路径下
10 *
11 * @param photoName 图片名称
12 * @param photoData 图片资源
13 * @param type 文件类型
14 * @return 图片路径
15 * @throws Exception
16 */
17 public String uploadPhoto(String photoName, String photoData, String type)
18 throws Exception {
19 // 对图片进行Base64解码
20 byte[] b = Base64.decodeBase64(photoData);
21 for (int i = 0; i < b.length; i++)
22 {
23 if(b[i] < 0)
24 { //调整异常数据
25 b[i] += 256;
26 }
27 }
28 // 生成图片
29 // 项目路径
30 String comPath = this.getClass().getResource("/").getPath() + type + "/";
31 String filePath = comPath + photoName;
32 File file = new File(filePath);
33 // 获取父文件
34 File parent = file.getParentFile();
35 // 若不存在创建父文件夹
36 if (!parent.exists()) {
37 parent.mkdirs();
38 }
39
40 // 输出文件流
41 OutputStream out = new FileOutputStream(file);
42 out.write(b);
43 out.flush();
44 out.close();
45
46 String path = filePath;
47 return path;
48 }