Javascript 如何在javascript中将dataURL转换为文件对象?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6850276/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 23:28:20  来源:igfitidea点击:

How to convert dataURL to file object in javascript?

javascriptjqueryfileapi

提问by kapv89

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.

我需要在 Javascript 中将 dataURL 转换为 File 对象,以便使用 AJAX 发送它。是否可以?如果是,请告诉我如何。

回答by Matthew

If you need to send it over ajax, then there's no need to use a Fileobject, only Bloband FormDataobjects are needed.

如果您需要通过ajax发送它,那么就不需要使用File对象,只需要BlobFormData对象。

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_decodefor example? Anyway, the standard-compliant code from this answerworks in Chrome 13 and WebKit nightlies:

正如我旁注的那样,您为什么不通过 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});


}

Then just append the blob to a new FormData object and post it to your server using ajax:

然后只需将 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);

回答by cuixiping

The BlobBuilderis deprecated and should no longer be used. Use Blobinstead of old BlobBuilder. The code is very clean and simple.

BlobBuilder已经过时,不应再使用。使用Blob而不是旧的 BlobBuilder。代码非常干净和简单。

File object is inherit from Blob object. You can use both of them with FormData object.

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});
}

use dataURLtoBlob() function to convert dataURL to blob and send ajax to server.

使用 dataURLtoBlob() 函数将 dataURL 转换为 blob 并将 ajax 发送到服务器。

for example:

例如:

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);


Another way:

其它的办法:

You can also use fetchto convert an url to a file object (file object has name/fileName property, this is different from blob object)

您还可以使用fetch将 url 转换为文件对象(文件对象具有 name/fileName 属性,这与 blob 对象不同)

The code is very short and easy to use. (works in Chrome and Firefox)

代码非常简短且易于使用。 (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});})
    );
}

Usage example 1: Just convert to file object

用法示例1:只需转换为文件对象

srcToFile(
    'data:text/plain;base64,aGVsbG8gd29ybGQ=',
    'hello.txt',
    'text/plain'
)
.then(function(file){
    console.log(file);
})

Usage example 2: Convert to file object and upload to server

使用示例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)
;

回答by EpokK

After some research I arrived on this one:

经过一番研究,我得到了这个:

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 dw = new DataView(ab);
    for(var i = 0; i < byteString.length; i++) {
        dw.setUint8(i, byteString.charCodeAt(i));
    }
    // write the ArrayBuffer to a blob, and you're done
    return new Blob([ab], {type: mimeString});
}

module.exports = dataURItoBlob;