是否可以将 base64 代码转换为文件,就像从输入类型文件中获取的一样?

Is there possible to convert a base64 code to a file like it has been got from input type file?

我想知道是否有办法像从 <input type="file"/>.

中获取的那样将 b64 字符串转换为文件

我有这个函数来做这样的事情:

function filefy(url, filename, mime_type) {
    return fetch(url)
            .then(res => res.arrayBuffer())
            .then(buf => new File([buf], filename, {type: mime_type}));
}

它 returns 一个像这样的文件对象:

为此,我以这种方式使用了 filefy 函数:

filefy("data:image/jpeg;base64," + image, 
    new Date().getTime()+'.jpg', 
    'image/jpeg'
).then(file => {
    console.log(file);
    console.log(new FileReader().readAsBinaryString(file));

    var fd = new FormData();

    fd.append('file[]', file);
    fd.append('type', 'galeria');
    fd.append('timestamp', vm.timestamp);
    fd.append('user_id', 2);

    console.warn(fd.get('file[]'));

    $http.post(my_api_url + 'uploadedthings', fd, {
        transformRequest: angular.identity,
        headers: {'Content-Type': undefined}
    }).success(response => {
        console.log('ok', response);
    }).error(error => {
        console.log('erro', error);
    });
});

我的 Laravel API 无法识别此文件格式。当我从我的网络客户端使用时(此代码已在 Cordova 应用程序中使用),在 <input type="file"/> 中它有效。

我已经打印了这个输入的文件格式,它看起来像:

您可以简单地使用 Blob,而不是 filefy 函数来创建虚拟文件对象:

var blob = new Blob([image], { type: "image/jpeg"});
fd.append('file[]', blob, new Date().getTime()+'.jpg');

您可能需要将图像的 base64 字符串表示形式转换为字节数组(或使用 canvas.toBlob)。

更多信息: https://developer.mozilla.org/en-US/docs/Web/API/FormData/Using_FormData_Objects https://developer.mozilla.org/en-US/docs/Web/API/Blob