【问题标题】:Angular download base64 file dataAngular下载base64文件数据
【发布时间】:2021-09-16 04:47:32
【问题描述】:

当我尝试在 Angular 上保存具有这种格式的 base64 文件时:

// receivedFile.file = "data:image/jpeg;base64,/9j/4AAQSkZJR..."

var a = document.createElement('a');
const blob = new Blob([receivedFile.file], {type: receivedFile.infos.type});
a.href = URL.createObjectURL(blob);
a.download = receivedFile.infos.name;
a.click(); 

这段代码给了我一个损坏的文件,我该怎么办?

【问题讨论】:

  • 你用什么类型的?
  • 不一样了。 png/pdf/txt/jpg
  • 你试过使用 file-saver-es 包吗?
  • 如果您的receivedFile 是评论所暗示的字符串 - 那么您认为您在此处使用receivedFile.infos.typereceivedFile.infos.name 访问的究竟是什么......?
  • 如果您已经有数据 URI,为什么要首先创建一个新的 blob? a.href = receivedFile.file 应该已经完成​​了这项工作,不是吗?

标签: javascript angular blob


【解决方案1】:

在 Angular(和一般情况下)中,我使用 file-saver

import { saveAs } from 'file-saver';
const blob = new Blob([receivedFile], {type: receivedFile.infos.type});
FileSaver.saveAs(blob, receivedFile.infos.name);

另外,尝试删除字符串的data:image/jpeg;base64, 部分:

receivedFile.file.replace("data:image/jpeg;base64," , "")

【讨论】:

  • 还是同样的问题。可能收到的文件格式不对?
  • 尝试从字符串的开头删除data:image/jpeg;base64,
  • @Galileoomega 不妨试试stackoverflow.com/questions/16245767/…
  • 啊,太好了,我已经编辑了我的答案,如果您愿意将其标记为已接受。
【解决方案2】:

解决这个问题:

  • 从收到的File.file 中删除了data:image/jpeg;base64
  • 使用函数atob()const byteCharacters = atob(receivedFile.file);
  • 然后制作 blob const blob = new Blob([byteCharacters], {type: this.receivedFile.infos.type});

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-12-14
    • 1970-01-01
    • 2018-07-23
    • 2021-04-24
    • 2019-11-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多