BlobBuilder 已弃用,不应再使用。使用 Blob 而不是旧的 BlobBuilder。代码非常干净简洁。
文件对象继承自 Blob 对象。您可以将它们与 FormData 对象一起使用。
function dataURLtoBlob(dataurl) {
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 Blob([u8arr], {type:mime});
}
使用 dataURLtoBlob() 函数将 dataURL 转换为 blob 并将 ajax 发送到服务器。
例如:
var dataurl = 'data:text/plain;base64,aGVsbG8gd29ybGQ=';
var blob = dataURLtoBlob(dataurl);
var fd = new FormData();
fd.append("file", blob, "hello.txt");
var xhr = new XMLHttpRequest();
xhr.open('POST', '/server.php', true);
xhr.onload = function(){
alert('upload complete');
};
xhr.send(fd);
另一种方式:
您也可以使用fetch 将url 转换为文件对象(文件对象具有name/fileName 属性,这与blob 对象不同)
代码非常简短且易于使用。 (works in Chrome and Firefox)
//load src and convert to a File instance object
//work for any type of src, not only image src.
//return a promise that resolves with a File instance
function srcToFile(src, fileName, mimeType){
return (fetch(src)
.then(function(res){return res.arrayBuffer();})
.then(function(buf){return new File([buf], fileName, {type:mimeType});})
);
}
使用示例1:只需转换为文件对象
srcToFile(
'data:text/plain;base64,aGVsbG8gd29ybGQ=',
'hello.txt',
'text/plain'
)
.then(function(file){
console.log(file);
})
使用示例2:转换为文件对象并上传到服务器
srcToFile(
'data:text/plain;base64,aGVsbG8gd29ybGQ=',
'hello.txt',
'text/plain'
)
.then(function(file){
console.log(file);
var fd = new FormData();
fd.append("file", file);
return fetch('/server.php', {method:'POST', body:fd});
})
.then(function(res){
return res.text();
})
.then(console.log)
.catch(console.error)
;