繁体   English   中英

Angular 下载 base64 文件数据

[英]Angular download base64 file data

当我尝试用这种格式在 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(); 

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

试试这个

 const downloadLink = document.createElement('a'); const fileName = 'sample.pdf'; downloadLink.href = linkSource; downloadLink.download = fileName; downloadLink.click();

在 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," , "")

这是将 base64 转换为 angular 中的可下载文件格式的代码。

例如,如果您的文件类型是 csv,那么下面是代码片段

 downloadFile(base64:any,fileName:any){ const src = `data:text/csv;base64,${base64}`; const link = document.createElement("a") link.href = src link.download = fileName link.click() link.remove() } //calling above function with some sample base64 data downloadFile("c21hbGxlcg==","demo.csv")

注意:文件类型可以是您根据需要提供的任何类型(在上面代码片段的src中)。这里我以 csv 文件为例。

所以通过调用上面的 function 你可以下载结果文件将从浏览器下载。

要解决此问题:

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM