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

发布于 2024-11-27 04:15:17 字数 77 浏览 2 评论 0原文

我需要将 dataURL 转换为 Javascript 中的 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.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(6

一腔孤↑勇 2024-12-04 04:15:17

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

正如我旁注的那样,为什么不直接通过 ajax 将 base64 字符串发送到服务器并将其转换为二进制服务器端,例如使用 PHP 的 base64_decode ?无论如何,这个答案中的符合标准的代码适用于 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});


}

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

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.

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


}

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);
过期情话 2024-12-04 04:15:17

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 对象不同)

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

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

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

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.

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 fetch to convert an url to a file object (file object has name/fileName property, this is different from blob object)

The code is very short and easy to use. (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

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

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)
;
零時差 2024-12-04 04:15:17

要从 dataURL 创建 Blob:

const response = await fetch(dataURL);
const blob = await response.blob(); 

要从 Blob 创建文件:

const file = new File(
  [blob],
  "fileName.jpg",
  {
    type: "image/jpeg",
    lastModified: new Date()
  }
);

To create a blob from a dataURL:

const response = await fetch(dataURL);
const blob = await response.blob(); 

To create a file from a blob:

const file = new File(
  [blob],
  "fileName.jpg",
  {
    type: "image/jpeg",
    lastModified: new Date()
  }
);
陌若浮生 2024-12-04 04:15:17

如果您确实想将 dataURL 转换为 File 对象。

您需要将 dataURL 转换为 Blob,然后将 Blob 转换为 File
该功能来自马修的回答。 (https://stackoverflow.com/a/7261048/13647044)

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

除此之外,您还可以在 < code>File 对象已初始化。 参考 File() 构造函数。

const resultFile = new File([blob], "file_name",{type:file.type,lastModified:1597081051454});

类型应为 [MIME][1] 类型(即 image/jpeg),我的示例中的最后修改值相当于 Mon Aug 10 2020 19: 37:31 GMT+0200(东欧标准时间)

If you really want to convert the dataURL into File object.

You need to convert the dataURL into Blob then convert the Blob into File.
The function is from answer by Matthew. (https://stackoverflow.com/a/7261048/13647044)

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

Other than that, you can have options on the File Object initialised. Reference to File() constructor.

const resultFile = new File([blob], "file_name",{type:file.type,lastModified:1597081051454});

The type should be [MIME][1] type(i.e. image/jpeg) and last modified value in my example is equivalent to Mon Aug 10 2020 19:37:31 GMT+0200 (Eastern European Standard Time)

风向决定发型 2024-12-04 04:15:17

在最新的浏览器中:

const dataURLtoBlob = (dataURL) => {
        fetch(dataURL)
            .then(res => res.blob())
            .then(blob => console.log(blob))
            .catch(err => console.log(err))
    }

In Latest browsers:

const dataURLtoBlob = (dataURL) => {
        fetch(dataURL)
            .then(res => res.blob())
            .then(blob => console.log(blob))
            .catch(err => console.log(err))
    }

孤独陪着我 2024-12-04 04:15:17

经过一番研究后,我得出了这个结论:

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;

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;

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文