base64上傳圖片儲存到資料庫

來源:互聯網
上載者:User

標籤:上傳   有助於   .com   file   reader   資料庫   logs   ref   one   

js實現圖片上傳預覽功能,使用base64編碼來實現

實現圖片上傳的方法有很多,這裡我們介紹比較簡單的一種,使用base64對圖片資訊進行編碼,然後直接將圖片的base64資訊存到資料庫。

但是對於系統中需要上傳的圖片較多時並不建議採用這種方式,我們一般會選擇存圖片路徑的方式,這樣有助於減小資料庫壓力,base64

編碼後的圖片資訊是一個很長的字串,一般我們使用longText類型來將其存入資料庫。

html代碼如下:

<div class="col-sm-6">

  <img id="headPortraitImgShow" src="img/defaultHeadPoint.jpg" width="160px" height="180px" />

  <input type="file" id="headPortraitUpload" style="margin-top:10px;">

</div>

javaScript代碼如下:

 

$("#headPortraitUpload").on("change",headPortraitListener);

 

 /*定義全域變數存貯圖片資訊*/
 var base64head="";

/*頭像上傳監聽*/

function headPortraitListener(e) {

    var img =document.getElementById(‘headPortraitImgShow‘);

      if(window.FileReader){

          var file  = e.target.files[0];

          var reader = newFileReader();

          if (file&& file.type.match(‘image.*‘)) {

             reader.readAsDataURL(file);

          } else {

             img.css(‘display‘, ‘none‘);

             img.attr(‘src‘, ‘‘);

          }

          reader.onloadend =function (e) {

         img.setAttribute(‘src‘, reader.result);

          base64head =reader.result;

        }

      }

}

 

效果預覽:預設圖片-----》

      

最後,將base64head提交到後台存入資料庫即可,下次從資料庫取出直接將該base64資訊放到img標籤的src裡面圖片就回顯出來了

 

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.