Angular - 使用 base64 上传/存储/下载文件

问题描述 投票:0回答:1

我正在使用 Angular 并尝试上传文件(存储在数据库中),然后下载该文件。我正在使用 Base 64 编码/解码。它看起来好像可以工作,但是在我下载文件后,当我尝试使用 Windows 默认图像查看器打开它时,它显示“看起来我们不支持这种格式”。文件不为空(大小 > 0)。 我哪里错了?我觉得可疑的一件事是我的变量解码在调试器中显示为类型 [object ArrayBuffer] 而不是字符串。

//像这样读入文件(例如jpeg文件):

   let fileReader = new FileReader();

    // Callback fxn for when the filereader's onload event fires (readAsBinaryString() below)
    fileReader.onload = async (e) => {

      // base64 encode the file contents
      let encoded = btoa(fileReader.result as string);
      // pass the encoded file content, type, and name to the API

      //store the file (i.e. encoded) to the database
  //Note that I compared this value to the value I retrieve from the database below and they are the same
    }

    // Now read the file contents. Note that this is an async operation and the onload callback will be called when it completes
    fileReader.readAsBinaryString(documentName);

//检索它 让 documentName = 'test.jpg'; 让编码文档 = xxx; //数据库中的编码字符串,与之前保存到数据库中的字符串相匹配 让 documentFormat = 'image/jpeg'; 让解码 = atob(encodedDocument);

    //download it
    const blob = new Blob([decoded], { type: documentFormat });
    let url = window.URL.createObjectURL(blob);
    let a = document.createElement('a');
    document.body.appendChild(a);
    a.setAttribute('style', 'display: none');
    a.href = url;
    a.download = documentName;
    a.click();
    window.URL.revokeObjectURL(url);
    a.remove();
angular download base64
1个回答
0
投票

好吧,明白了。 atob 不知何故无法工作。 关键是使用这个url来下载它。 让 url = '数据:' + documentFormat + ';charset=utf-8;base64,' + 编码文档;

© www.soinside.com 2019 - 2024. All rights reserved.