urlToFile = (url) => {// url是文件的url地址
let image = new Image();
image.src = url;
image.onload = function () {
let base64 = getBase64Image(image),
file = btof(base64, "noChange");
console.log(file) // 这个file就是转换成功的file文件
};
},
/** url 转换成img */
getBase64Image = (img) => {
let canvas = document.createElement("canvas");
canvas.width = img.width;
canvas.height = img.height;
let ctx = canvas.getContext("2d");
ctx.drawImage(img, 0, 0, img.width, img.height);
let ext = img.src.substring(img.src.lastIndexOf(".") + 1).toLowerCase(),
dataURL = canvas.toDataURL("image/" + ext);
return dataURL;
},
/** base64 转换成file */
btof = (data, fileName) => {
const dataArr = data.split(","),
byteString = atob(dataArr[1]),
options = {
type: "image/jpeg",
endings: "native"
},
u8Arr = new Uint8Array(byteString.length);
for (let i = 0; i < byteString.length; i++) {
u8Arr[i] = byteString.charCodeAt(i);
}
return new File([u8Arr], fileName + ".jpg", options);
},