jquery上傳base64位圖片


 
         

  <img id="articleImg" width="180" height="100">
  <input type="file" value="上傳" id="articleImg


1
$('#articleImgBtn').change(function(){ 2 run(this, function (data) { 3 uploadImage(data); 4 }); 5 }); 6 7 function run(input_file, get_data) { 8 /*input_file:文件按鈕對象*/ 9 /*get_data: 轉換成功后執行的方法*/ 10 if (typeof (FileReader) === 'undefined') { 11 alert("抱歉,你的瀏覽器不支持 FileReader,不能將圖片轉換為Base64,請使用現代瀏覽器操作!"); 12 } else { 13 try { 14 /*圖片轉Base64 核心代碼*/ 15 var file = input_file.files[0]; 16 //這里我們判斷下類型如果不是圖片就返回 去掉就可以上傳任意文件 17 if (!/image\/\w+/.test(file.type)) { 18 alert("請確保文件為圖像類型"); 19 return false; 20 } 21 var reader = new FileReader(); 22 reader.onload = function () { 23 get_data(this.result); 24 } 25 reader.readAsDataURL(file); 26 } catch (e) { 27 alert('圖片轉Base64出錯啦!' + e.toString()) 28 } 29 } 30 } 31 32 function uploadImage(img) { 33 //判斷是否有選擇上傳文件 34 var imgPath = $("#articleImgBtn").val(); 35 if (imgPath == "") { 36 alert("請選擇上傳圖片!"); 37 return; 38 } 39 //判斷上傳文件的后綴名 40 var strExtension = imgPath.substr(imgPath.lastIndexOf('.') + 1); 41 if (strExtension != 'jpg' && strExtension != 'gif' 42 && strExtension != 'png' && strExtension != 'bmp') { 43 alert("請選擇圖片文件"); 44 return; 45 } 46 $.ajax({ 47 type: "POST", 48 url: ’上傳圖片接口‘, 49 data: { token: token,file: img.substr(img.indexOf(',') + 1)}, //視情況將base64的前面字符串data:image/png;base64,刪除 50 cache: false, 51 success: function(data) { 52 alert("上傳成功"); 53 $("#articleImg").attr('src', JSON.parse(data).imageUrl); 54 }, 55 error: function(XMLHttpRequest, textStatus, errorThrown) { 56 alert("上傳失敗,請檢查網絡后重試"); 57 } 58 }); 59 }

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM