kap*_*v89 37 javascript jquery fileapi
我需要在Javascript中将dataURL转换为File对象,以便使用AJAX将其发送出去.可能吗?如果是,请告诉我如何.
Mat*_*hew 51
如果您需要通过AJAX发送它,那么就没有必要使用一个File对象,只有Blob和FormData需要的对象.
正如我的旁注,为什么不通过ajax将base64字符串发送到服务器并将其转换为二进制服务器端,base64_decode例如使用PHP ?无论如何,这个答案的标准兼容代码适用于Chrome 13和WebKit nightlies:
function dataURItoBlob(dataURI) {
// convert base64 to raw binary data held in a string
// doesn't handle URLEncoded DataURIs - see SO answer #6850276 for code that does this
var byteString = atob(dataURI.split(',')[1]);
// separate out the mime component
var mimeString = dataURI.split(',')[0].split(':')[1].split(';')[0];
// write the bytes of the string to an ArrayBuffer
var ab = new ArrayBuffer(byteString.length);
var ia = new Uint8Array(ab);
for (var i = 0; i < byteString.length; i++) {
ia[i] = byteString.charCodeAt(i);
}
//Old Code
//write the ArrayBuffer to a blob, and you're done
//var bb = new BlobBuilder();
//bb.append(ab);
//return bb.getBlob(mimeString);
//New Code
return new Blob([ab], {type: mimeString});
}
Run Code Online (Sandbox Code Playgroud)
然后将blob附加到新的FormData对象并使用ajax将其发布到您的服务器:
var blob = dataURItoBlob(someDataUrl);
var fd = new FormData(document.forms[0]);
var xhr = new XMLHttpRequest();
fd.append("myFile", blob);
xhr.open('POST', '/', true);
xhr.send(fd);
Run Code Online (Sandbox Code Playgroud)
cui*_*ing 42
该BlobBuilder已经过时,不应再使用.使用Blob而不是旧的BlobBuilder.代码非常简洁.
File对象继承自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});
}
Run Code Online (Sandbox Code Playgroud)
使用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);
Run Code Online (Sandbox Code Playgroud)
其他方式:
您还可以使用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});})
);
}
Run Code Online (Sandbox Code Playgroud)
用法示例1:只需转换为文件对象
srcToFile(
'data:text/plain;base64,aGVsbG8gd29ybGQ=',
'hello.txt',
'text/plain'
)
.then(function(file){
console.log(file);
})
Run Code Online (Sandbox Code Playgroud)
用法示例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)
;
Run Code Online (Sandbox Code Playgroud)
要从 dataURL 创建 blob:
const blob = await (await fetch(dataURL)).blob();
Run Code Online (Sandbox Code Playgroud)
要从 blob 创建文件:
const file = new File([blob], 'fileName.jpg', {type:"image/jpeg", lastModified:new Date()});
Run Code Online (Sandbox Code Playgroud)
小智 6
如果你确实想将 dataURL 转换为File对象。
您需要将 dataURL 转换为Blob然后将其转换Blob为File。该功能来自马修的回答。(/sf/answers/508273391/)
function dataURItoBlob(dataURI) {
// convert base64 to raw binary data held in a string
// doesn't handle URLEncoded DataURIs - see SO answer #6850276 for code that does this
var byteString = atob(dataURI.split(',')[1]);
// separate out the mime component
var mimeString = dataURI.split(',')[0].split(':')[1].split(';')[0];
// write the bytes of the string to an ArrayBuffer
var ab = new ArrayBuffer(byteString.length);
var ia = new Uint8Array(ab);
for (var i = 0; i < byteString.length; i++) {
ia[i] = byteString.charCodeAt(i);
}
return new Blob([ab], { type: mimeString });
}
const blob = dataURItoBlob(url);
const resultFile = new File([blob], "file_name");
Run Code Online (Sandbox Code Playgroud)
除此之外,您还可以对File初始化的对象进行选项。引用File() 构造函数。
const resultFile = new File([blob], "file_name",{type:file.type,lastModified:1597081051454});
Run Code Online (Sandbox Code Playgroud)
类型应该是[MIME][1]type(ie image/jpeg) 并且我的示例中的最后修改值相当于Mon Aug 10 2020 19:37:31 GMT+0200 (Eastern European Standard Time)
| 归档时间: |
|
| 查看次数: |
56441 次 |
| 最近记录: |