IE 11在Angular 2中无法从字节数组创建文件对象

11

有人能告诉我为什么IE11在最后一行抛出错误吗?

this.document = this.control.value;
  const bytes = 
this.documentService.base64toBytes(this.document.documentBlob.documentData, 
       this.document.documentDataFormat);
const file = new File(bytes, this.document.documentName, { type: 
       this.document.documentDataFormat });

这在Chrome和Firefox中都可以正常工作。IE则抛出对象错误 -

Object doesn't support this action.

2
根据http://caniuse.com/#search=file的说明,IE11似乎不支持file构造函数。 - silentsod
糟糕!那么您建议采取什么解决方法呢? - Mayeed
3个回答

9

文件是Blob加上元属性,因此您可以像这样添加必要的属性:

let blob = this.documentService.base64toBytes(this.document.documentBlob.documentData, this.document.documentDataFormat);
// and add the meta properties
blob['lastModifiedDate'] = new Date();
blob['name'] = 'fileName';

然后这个blob就是一个文件。

1
哇,真的是那么简单。经过20分钟疯狂搜索,在不使用文件构造函数的情况下将我的 Blob 转换为文件真的很容易。谢谢! - SeanMC
1
@SeanKPS 没关系,我很高兴能够帮助! - Brahim LAMJAGUAR
1
谢谢!你真是救星啊!!我喜欢这个解决方案,比标记为答案的那个更好。点赞!:) - aj go
@ajgo 很高兴能帮到你 ;) - Brahim LAMJAGUAR

3

由于IE不支持File API的构造函数,我想出了以下解决方法。希望这对未来的其他人有所帮助 -

const bytes = this.documentService.base64toBytes(this.document.documentBlob.documentData, this.document.documentDataFormat);
let file: File;
try {
  file = new File(bytes, this.document.documentName, { type: this.document.documentDataFormat });

  if (this.uploader.isFile(file)) {
    this.uploader.addToQueue([file]);
  }
} catch (err) { // Workaround for IE 11
  const blob = this.documentService.base64ToBlob(this.document.documentBlob.documentData,
    this.document.documentDataFormat);
  file = this.documentService.blobToFile(blob, this.document.documentName);
  this.uploader.addToQueue([file]);

1
为了在IE11中简化代码,你可以将"file = new File(bytes, this.document.documentName, { type: this.document.documentDataFormat });"替换为"new Blob(bytes, { type: this.document.documentDataFormat })"。 - Marco C.
1
documentService.blobToFile 是什么样子? - SeanMC
1
@Brahim-LAMJAGUAR的回答对我有用。 - SeanMC

0

这个解决方案对我来说很有效,可以创建文件而不是使用file()

let file = <File>Object.assign(new Blob([bytes]), { name: fileName });

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