我有一个Angular应用程序,用户可以下载他们上传的一些文档(.jpg、.mp4和.pdf).基本上,文件的下载是这样工作的:调用一个服务,该服务返回有关文件的一些信息,如base64中的文件名、类型、大小和内容.

这是用户单击下载按钮时组件中的下载方法:

downloadDocument(doc: Document) {
  this._subDownDocument = this.service.getDocument(doc).subscribe((resp: Document) => {
    var link = document.createElement("a");
    link.download = resp.fileName;
    link.target = "_blank";

    // Construct the URI
    link.href = resp.url;//Url is the content of the file in base64
    document.body.appendChild(link);
    link.click();

    // Cleanup the DOM
    document.body.removeChild(link);
  });
}

对于高达12mb的文件,它工作得非常好.但当文件较大时,下载无法启动,服务会正确地提供文件,但我不知道为什么下载无法启动.浏览器控制台中不会显示任何错误.

这个问题只会发生在Firefox上,因为在Google Chrome上它可以正常工作.你知道我该怎么解决这个问题吗?

推荐答案

我通过安装FileSaver.js解决了这个问题.它用于大文件目的.

npm install file-saver --save

并将我的下载方法更改为:

downloadDocument(doc: Document) {
  this._subDownDocument = this.service.getDocument(doc).subscribe((resp: Document) => {

   //Url is the content of the file in base64
   fileSaver.saveAs(this.b64toBlob(resp.url, resp.type), resp.fileName);

  });
}

private b64toBlob(dataURI, type) {

  var byteString = atob(dataURI.split(',')[1]);
  var ab = new ArrayBuffer(byteString.length);
  var ia = new Uint8Array(ab);

  for (var i = 0; i < byteString.length; i++) {
    ia[i] = byteString.charCodeAt(i);
  }
  return new Blob([ab], { type: type });
}

Javascript相关问答推荐

如何在非独立组件中使用独立组件?

创建私有JS出口

我在这个黑暗模式按钮上做错了什么?

从mat—country—select获取整个Country数组

防止用户在selectizeInput中取消 Select 选项

使用javascript将Plotly Expandable Sparkline转换为HighCharter Plot在bslib卡中

将本机导航路由react 到导航栏中未列出的屏幕?

如何从调整大小/zoom 的SVG路径定义新的d属性?""

类构造函数忽略Reaction Native中的可选字段,但在浏览器中按预期工作

将Node.js包发布到GitHub包-错误ENEEDAUTH

Jest toHaveBeenNthCalledWith返回当前设置的变量值,而不是调用时的值

如何在FastAPI中为通过file:/URL加载的本地HTML文件启用CORS?

AddEventListner,按键事件不工作

删除元素属性或样式属性的首选方法

如何在和IF语句中使用||和&;&;?

无法重定向到Next.js中的动态URL

TabNavigator和StackNavigator之间的Reaction Native中的导航问题

需要刷新以查看Mern堆栈应用程序中的更改

将字体样式应用于material -UI条形图图例

将Windows XP转换为原始数据以在html前端中显示