input标签file文件上传图片本地预览(转载)

 

<input type="file" name="img-up" id="img-up" value="" />

  

$("#img-up").on("change",function () {
                if(this.files[0]){
                    getImgBase64Data(this.files[0], function (result) {
                        console.log(result);
                        
                    });
                }

            });
            function getImgBase64Data(file, callback) {
                var reader = new FileReader();
                reader.onload = function (e) {
                    callback(e.target.result);
                };
                reader.readAsDataURL(file); // 读取完后会调用onload方法
            }
		

  

方法二:

		//取得该文件的url 
		function getObjectURL(file) { 
		  var url = null ; 
		  if (window.createObjectURL!=undefined) { 
		    url = window.createObjectURL(file) ; 
		  } else if (window.URL!=undefined) { 
		    url = window.URL.createObjectURL(file) ; 
		  } else if (window.webkitURL!=undefined) { 
		    url = window.webkitURL.createObjectURL(file) ; 
		  } 
		  return url ; 
		} 

  

 将base64的图片,转换回 file 对象

// base 64 转 blob
let dataURLtoFile = function (b64Data,filename) {
   filename = filename || "test.png";
  let mime = "image/png";
  var bstr = atob(b64Data.replace(/^data:image\/(png|jpeg|jpg);base64,/, ''));
  var n = bstr.length; 
  var u8arr = new Uint8Array(n);
  while(n--){
      u8arr[n] = bstr.charCodeAt(n);
  }
  //转换成file对象
  return new File([u8arr], filename, {type:mime});
  //转换成成blob对象
  //return new Blob([u8arr],{type:mime});
  return blob;

}

 

文章转自于 https://www.cnblogs.com/muamaker/p/6758219.html

posted @ 2021-03-16 14:18  fanbu  阅读(287)  评论(0编辑  收藏  举报