儲存頭像- vue專案-base64字串轉圖片
阿新 • • 發佈:2018-11-06
<img :onerror="errpic" class="customerHead" :src="param.customerHead" alt="">
data() {
return {
param:{
id:"",
customerHead: "",
}
}
}
let _this = this let files = e.target.files[0] if (files.size/(1024*1024) > 2) { this.open('上傳的圖片不可大於2M!') return false; } var reader = new FileReader(); reader.onload = function (e) { var base64 = e.target.result; _this.param.customerHead = base64 //console.log(base64) } //前端全棧開發學習交流圈 if(files) {//866109386 reader.readAsDataURL(files); }
如果修改頭像,向後臺傳base64字串,否則會傳原圖片路徑,後臺判斷是否是base64字串.
如果是base64字串,則對base64字串進行處理,在後臺伺服器生成圖片.此處需要對base64字串進行處理,如圖所示,刪除藍框部分,留逗號之後的內容.
若為圖片路徑,則不需要進行處理,直接返回圖片路徑即可.
@Value("${upload.image.path}") private String filePath; //base64字串轉化成圖片 headerImgPath:http://+ip+:埠號 public String generateImage(String imgStr,String headerImgPath,String cusID) { //對位元組陣列字串進行Base64解碼並生成圖片 if (imgStr == null) //影象資料為空 return "../picclife/static/custom.png"; BASE64Decoder decoder = new BASE64Decoder(); try { //判斷是base64字串還是圖片路徑 if(imgStr.substring(0,5).equals("data:")){ //Base64解碼 byte[] b = decoder.decodeBuffer(imgStr.substring(imgStr.indexOf(",") + 1)); for(int i=0;i<b.length;++i) { if(b[i]<0) {//調整異常資料 b[i]+=256; } } //生成圖片 String imgFilePath = filePath+"/headerImg/"+cusID+".jpg";//新生成的圖片 OutputStream out = new FileOutputStream(imgFilePath); out.write(b); //前端全棧交流學習圈:866109386 out.flush(); //面向1-3年前端開發人員 out.close();//幫助突破技術瓶頸,提升思維能力 return headerImgPath+"headerImg/"+cusID+".jpg"; }else{ return imgStr; } } catch (Exception e) { return "../picclife/static/custom.png"; } }