gpt4 book ai didi

javascript - 在 javascript 中创建文件时获取大小 0

转载 作者:行者123 更新时间:2023-12-02 23:40:43 26 4
gpt4 key购买 nike

我正在尝试从 Ionic 中的相机插件获得的一些 Base64 数据创建一个文件。我正在使用从另一个 stackoverflow 的答案中获得的函数。问题是创建的文件大小为:0,并且 name 属性似乎是我在创建时传递的 Uint8array。

这是转换Base64数据的函数:(前两行被注释,因为数据没有“data:image/jpeg;base64,”开头)

_dataURLtoFile(dataurl, filename) {
let //arr = dataurl.split(','),
//mime = arr[0].match(/:(.*?);/)[1],
bstr = atob(dataurl),
n = bstr.length,
u8arr = new Uint8Array(n);

while(n--){
u8arr[n] = bstr.charCodeAt(n);
}
return new File([u8arr], filename, {type:'image/jpeg'});
}

这是我在控制台中得到的内容:

File {name: Array(1), localURL: "archivo", type: {…}, lastModified: null, lastModifiedDate: null, …}
end: 0
lastModified: null
lastModifiedDate: null
localURL: "archivo"
name: [Uint8Array(268175)]
size: 0
start: 0
type: {type: "image/jpeg"}
__proto__: Object

最佳答案

根据对 File 已被覆盖的问题的评论,我修改了该函数以使用 Blob 而不是 File,然后它将生成一个文件

为了演示目的,我还用另一个函数覆盖了默认的File。我还让它在 DOM 中输出文件,以显示它已加载正确的数据。

window.File = () => 'brokenfilefunction'
function dataURLtoFile(dataurl, filename) {
let bstr = atob(dataurl),
n = bstr.length,
u8arr = new Uint8Array(n);

while(n--){
u8arr[n] = bstr.charCodeAt(n);
}
// Something has overwritten File, so you can't use it
// return new File([u8arr], filename, {type:'image/jpeg'});

// Adding the blob to FormData converts it to an actual file
const formData = new FormData();
const blob = new Blob([u8arr], { type: 'image/jpeg' });
formData.append(filename, blob);
// Instead of getting the file, you could just send the formdata object in your request
const actualFile = formData.entries().next().value[1];

return actualFile;
}

const image = 'iVBORw0KGgoAAAANSUhEUgAAAAUAAAAFCAYAAACNbyblAAAAHElEQVQI12P4//8/w38GIAXDIBKE0DHxgljNBAAO9TXL0Y4OHwAAAABJRU5ErkJggg==';


const file = dataURLtoFile(image, 'name');
console.log(file);

// Display image in dom for demo
const fr = new FileReader();
fr.onload = function () {
document.getElementById('image').src = fr.result;
}
fr.readAsDataURL(file);
File has correctly been initialized to red dot:
<img id="image" style="width: 10px; height: 10px;" />

关于javascript - 在 javascript 中创建文件时获取大小 0,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56092175/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com