1 /** 2 * [getBase64 转换成base64] 3 * @param {[String]} imgUrl [图片地址] 4 */ 5 function getBase64(imgUrl) { 6 7 window.URL = window.URL || window.webkitURL; 8 9 var xhr = new XMLHttpRequest(); 10 11 xhr.open("get", imgUrl, true); 12 13 // 返回的数据类型 14 xhr.responseType = "blob"; 15 16 xhr.onload = function () { 17 18 if (this.status == 200) { 19 20 // 得到一个blob对象 21 var blob = this.response; 22 23 console.log(blob); 24 25 // 文件读取 26 let fileReader = new FileReader(); 27 28 fileReader.onloadend = function (e) { // onloadend 当读取操作完成时调用,不管是成功还是失败 29 30 let base64 = e.target.result; 31 32 console.log(base64); //输出base64 33 34 }; 35 36 fileReader.readAsDataURL(blob); // 异步读取文件内容,结果用data:url的字符串形式表示 37 38 } 39 40 } 41 42 xhr.send(); 43 44 }