如何在javascript中将dataURL转换为文件对象? [英] How to convert dataURL to file object in javascript?
问题描述
我需要在Javascript中将dataURL转换为File对象,以便使用AJAX将其发送出去。可能吗?如果是,请告诉我如何。
I need to convert a dataURL to a File object in Javascript in order to send it over using AJAX. Is it possible? If yes, please tell me how.
推荐答案
如果你需要通过ajax发送它,那么就没有必要使用文件
对象,只需要 Blob
和 FormData
对象。
If you need to send it over ajax, then there's no need to use a File
object, only Blob
and FormData
objects are needed.
正如我的旁注,为什么不通过ajax将base64字符串发送到服务器并使用PHP的将其转换为二进制服务器端例如base64_decode
?无论如何,来自此答案的符合标准的代码适用于Chrome 13和WebKit nightlies:
As I sidenote, why don't you just send the base64 string to the server over ajax and convert it to binary server-side, using PHP's base64_decode
for example? Anyway, the standard-compliant code from this answer works in Chrome 13 and 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});
}
然后只需将blob附加到新的FormData对象并使用ajax将其发布到您的服务器:
Then just append the blob to a new FormData object and post it to your server using 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);
这篇关于如何在javascript中将dataURL转换为文件对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!