在Microsoft Edge中实例化文件对象

16

我试图使用File API从Blob对象创建图像文件,然后将其添加到表单中通过XHR发送。在Chrome中运作良好,但在Microsoft Edge中会导致应用程序崩溃。

let file = new File([blobContent], "image.png");

let form = new FormData();
form.append("file", file);

有没有File API的替代方案或附加文件到表单的解决方法?如果我只是将Blob添加到表单中,它不会被识别为图像。

谢谢!


同样的问题。 我想创建一个带有字符串内容和名称的文件。 在其他每个浏览器中都可以正常工作,但在EDGE中会抛出“期望函数”的错误:filename ='a';data ='b'; new File(new Blob([data])) - masterxilo
2个回答

20

目前,IE11和Edge支持FileAPI,但不支持File构造函数。

在您发布的链接中,有关于IE和Edge的说明,说明它们不支持File构造函数。我遇到了同样的问题,我的解决方法是使用Blob代替File,然后设置blob的类型。

var blob = new Blob([blobContent], {type : 'image/jpeg'});

3
如果您设置 blob.name = "image.png",浏览器会将其视为 File,同样的方式处理它。 - morloch
好的解决方案,但在这种情况下,你如何测试变量的类型是否为文件?而且我还需要区分 blob 和文件... - Tony Bogdanov

13

这是我所做的并且有效

// to change Blob to File
private blobToFile(theBlob: Blob, fileName: string): File {
   const b: any = theBlob;
   b.lastModifiedDate = new Date();
   b.name = fileName;
   return b as File;
}

let file;
if (!navigator.msSaveBlob) { // detect if not Edge
   file = new File([b], document.originalName, { type: document.mimeType });
} else {
   file = new Blob([b], { type: document.mimeType });
   file = this.blobToFile(file, document.originalName);
}

现在可以通过在Edge或其他浏览器中将变量文件作为文件来继续使用。


对我没用。Microsoft Edge 44.18362.449.0,Microsoft EdgeHTML 18.18363。 - icguy

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接