直接看代码
imgUrlToFile(url) {var self = this;var imgLink = url;var tempImage = new Image();//如果图片url是网络url,要加下一句代码tempImage.crossOrigin = "*";//跨域不可用tempImage.onload = function() {var base64 = self.getBase64Image(tempImage);//console.log(base64);imgblob = self.base64toBlob(base64);//获取原文件名称var filename = self.getFileName(self.ruleForm.coverUrl);self.ruleForm.coverFile = self.blobToFile(imgblob, filename);};tempImage.src = imgLink;
},
getBase64Image(img) {//通过canvas绘制图片转base64var canvas = document.createElement("canvas");canvas.width = img.width;canvas.height = img.height;var ctx = canvas.getContext("2d");ctx.drawImage(img, 0, 0, img.width, img.height);var ext = img.src.substring(img.src.lastIndexOf(".") + 1).toLowerCase();var dataURL = canvas.toDataURL("image/" + ext);return dataURL;
},
base64toBlob(base64) {//base64转Bloblet arr = base64.split(","),mime = arr[0].match(/:(.*?);/)[1],bstr = atob(arr[1]),n = bstr.length,u8arr = new Uint8Array(n);while (n--) {u8arr[n] = bstr.charCodeAt(n);}return new Blob([u8arr], { type: mime });
},
blobToFile(blob, filename) {//Blob转file对象// edge浏览器不支持new File对象,所以用以下方法兼容blob.lastModifiedDate = new Date();blob.name = filename;return blob;
},
getFileName(url) {// 获取到文件名let pos = url.lastIndexOf("/"); // 查找最后一个/的位置return url.substring(pos + 1); // 截取最后一个/位置到字符长度,也就是截取文件名
},//imgUrlToFile(),调用该方法就可以得到file对象