base64的圖片格式在存儲(chǔ)時(shí)是很占空間的颊糜,所以上傳服務(wù)器后保存圖片鏈接是個(gè)很不錯(cuò)的選擇棍好;代碼如下:
public String uploadImg(String baseImg){
String url = "";
try {
String rootPath = "";
String path = "";
String random = "";
try {
//對(duì)于base64格式的圖片锈麸,要去掉開(kāi)頭的部分
int dex = baseImg.indexOf("base64,");
baseImg = baseImg.substring(dex + 7);
//將圖片信息轉(zhuǎn)換為字節(jié)數(shù)組
byte[] arr = Base64Decoder.decodeToBytes(baseImg);
random = UUID.randomUUID().toString() + ".jpg";
String root = PathKit.getWebRootPath();
path = "/upload/";
rootPath = root + path;
File targetDir = new File(rootPath);
if (!targetDir.exists()) {
targetDir.mkdirs();
}
OutputStream out = new FileOutputStream(rootPath + random);
//循環(huán)寫出歉胶,確保文件寫完
for (int i = 0; i < arr.length; i++) {
out.write(arr[i]);// 逐字節(jié)寫文件
}
out.flush();
out.close();
} catch (Exception e) {
e.printStackTrace();
}
//測(cè)試地址(地址自定義)
url = "http://localhost:8080/kd_admin/upload/"+ random;
} catch (Exception e) {
url = null;
e.printStackTrace();
}
return url;
}