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 }