1、 fetch api请求,重点都是 responseType 要设置为blob,再使用 FileReader 的 readAsDataURL 方法把 blob 转成 base64
getBase64 (imgUrl, callback) {fetch(imgUrl, {responseType: 'blob'}).then(response => {return response.blob();}).then(blob => {let oFileReader = new FileReader();oFileReader.onloadend = function (e) {// base64结果const base64 = e.target.result// console.log(base64);callback(base64)};oFileReader.readAsDataURL(blob);});}
2、使用new XMLHttpRequest();
getBase64(imgUrl) {let xhr = new XMLHttpRequest();xhr.open('get', '/xxx.jpg', true);// 重点1xhr.responseType = 'blob';xhr.onload = function() {if (this.status == 200) {//得到一个blob对象let blob = this.response;// 重点2let oFileReader = new FileReader();oFileReader.onloadend = function(e) {// 结果const base64 = e.target.result};oFileReader.readAsDataURL(blob);}};xhr.send();
},