Cách 1: chỉ hoạt động cho dataURL, không hoạt động cho các loại url khác.
function dataURLtoFile(dataurl, filename) {
var arr = dataurl.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 File([u8arr], filename, {type:mime});
}
//Usage example:
var file = dataURLtoFile('data:image/png;base64,......', 'a.png');
console.log(file);
Way 2: làm việc cho bất kỳ loại url, (url http, dataURL, blobURL, vv ...)
//return a promise that resolves with a File instance
function urltoFile(url, filename, mimeType){
mimeType = mimeType || (url.match(/^data:([^;]+);/)||'')[1];
return (fetch(url)
.then(function(res){return res.arrayBuffer();})
.then(function(buf){return new File([buf], filename, {type:mimeType});})
);
}
//Usage example:
urltoFile('data:image/png;base64,......', 'a.png')
.then(function(file){
console.log(file);
})
Cả hai công trình trong Chrome và Firefox.
về thuộc tính nào bạn muốn so sánh chúng? –
để xem chúng tương tự như thế nào là – Bonik
, bạn có thể sử dụng FileReader trên các đốm màu và bạn có thể nạp một blob từ chuỗi nhị phân hoặc bộ đệm mảng. có những giải pháp ở đây cho điều đó. – dandavis