将数据 URI 转换为文件,然后附加到 FormData [英] Convert Data URI to File then append to FormData

查看:33
本文介绍了将数据 URI 转换为文件,然后附加到 FormData的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在尝试重新实现一个 HTML5 图片上传器,比如 在 Mozilla Hacks 网站上,但它适用于 WebKit 浏览器.部分任务是从 canvas 对象中提取图像文件并将其附加到 FormData 用于上传的对象.

I've been trying to re-implement an HTML5 image uploader like the one on the Mozilla Hacks site, but that works with WebKit browsers. Part of the task is to extract an image file from the canvas object and append it to a FormData object for upload.

问题是,虽然 canvas 具有 toDataURL 函数来返回图像文件的表示,但 FormData 对象只接受来自 文件 API.

The issue is that while canvas has the toDataURL function to return a representation of the image file, the FormData object only accepts File or Blob objects from the File API.

Mozilla 解决方案在 canvas 上使用了以下仅限 Firefox 的功能:

The Mozilla solution used the following Firefox-only function on canvas:

var file = canvas.mozGetAsFile("foo.png");

...在 WebKit 浏览器上不可用.我能想到的最佳解决方案是找到某种方法将 Data URI 转换为 File 对象,我认为这可能是 File API 的一部分,但我一生都找不到这样做的方法.

...which isn't available on WebKit browsers. The best solution I could think of is to find some way to convert a Data URI into a File object, which I thought might be part of the File API, but I can't for the life of me find something to do that.

有可能吗?如果没有,还有其他选择吗?

Is it possible? If not, any alternatives?

谢谢.

推荐答案

在尝试了一些东西后,我自己设法解决了这个问题.

After playing around with a few things, I managed to figure this out myself.

首先,这会将 dataURI 转换为 Blob:

First of all, this will convert a dataURI to a Blob:

function dataURItoBlob(dataURI) {
    // convert base64/URLEncoded data component to raw binary data held in a string
    var byteString;
    if (dataURI.split(',')[0].indexOf('base64') >= 0)
        byteString = atob(dataURI.split(',')[1]);
    else
        byteString = unescape(dataURI.split(',')[1]);

    // separate out the mime component
    var mimeString = dataURI.split(',')[0].split(':')[1].split(';')[0];

    // write the bytes of the string to a typed array
    var ia = new Uint8Array(byteString.length);
    for (var i = 0; i < byteString.length; i++) {
        ia[i] = byteString.charCodeAt(i);
    }

    return new Blob([ia], {type:mimeString});
}

从那里,将数据附加到表单以便将其作为文件上传很容易:

From there, appending the data to a form such that it will be uploaded as a file is easy:

var dataURL = canvas.toDataURL('image/jpeg', 0.5);
var blob = dataURItoBlob(dataURL);
var fd = new FormData(document.forms[0]);
fd.append("canvasImage", blob);

这篇关于将数据 URI 转换为文件,然后附加到 FormData的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆