1. 程式人生 > >jq獲取圖片並換換為base64

jq獲取圖片並換換為base64

html程式碼:

<input type="file" id="file1"/>

jq程式碼:

$('#file1').change(function(e){
  var imgBox = e.target;
  uploadImg($('.file1'), imgBox)
});
function uploadImg(element, tag ) {
  var file = tag.files[0];
  var imgSrc;
  if (!/image\/\w+/.test(file.type)) {
  alert("請上傳圖片!");
  return false;
  }
  var reader = new FileReader();
  reader.readAsDataURL(file);
  reader.onload = function() {
  //console.log(this.result);
  imgSrc = this.result;
  $(element).attr("src", imgSrc);
  };
}