jquery上傳base64位元影像片

來源:互聯網
上載者:User

標籤:input   error   run   alert   bst   url   hang   pat   網路   


  <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 }

 

jquery上傳base64位元影像片

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.