【问题标题】:Angular 7 correctly upload doc/docx fileAngular 7 正确上传 doc/docx 文件
【发布时间】:2021-02-18 05:15:45
【问题描述】:

我在上传 doc 和 docx 文件时遇到问题,因为在将文件转换为 base64 时无法获得正确的文件类型。这是我的输入:

  <input
    accept=".pdf,.txt,.doc,.docx"
    type="file"
    (change)="onNativeInputFileSelect($event)"
    #inputFile
    hidden
  />

在我的方法中,我这样做:

  onNativeInputFileSelect(event) {
    if (event.target.value) {
      const file: File = event.target.files[0];
      this.changeFile(file).then((base64: string): any => {
        this.attachment.content= base64;
        this.uploadFile(this.attachment);
      });
    }
  }

然后在“uploadFile”中,我将文件作为 base 64 字符串发送到服务器。
changeFile 方法是这样的:

  changeFile(file) {
    return new Promise((resolve, reject) => {
      const reader = new FileReader();
      reader.readAsDataURL(file);
      reader.onload = () => resolve(reader.result);
      reader.onerror = (error) => reject(error);
    });
  }

这适用于 pdf 或 txt 文件,但是当我上传 .doc 或 .docx 文件时,我会得到这个 base64 字符串:

data:application/octet-stream;base64,0M8R4KGxGuEAA[...]

而对于 pdf,我正确地拥有:

data:application/pdf;base64,JVBERi0xLjQKJeLjz9MKMS

这意味着当我尝试下载文件时,我没有得到正确的类型,因为我有 application/octet-stream,所以我无法为文件添加正确的扩展名。
我尝试通过传递给输入组件的accept 属性:

application/msword,application/pdf,text/plain,application/vnd.openxmlformats-officedocument.wordprocessingml.document

但没有任何改变,Window 的文件选择器只建议我 .pdf 和 .txt 文件

编辑

This is a working stackblitz

【问题讨论】:

  • 这在我的 Mac 上运行良好。 "CONTENUTO 数据:application/vnd.openxmlformats-officedocument.wordprocessingml.document;base64,UEsDBB...."

标签: file-upload angular7 angular-input


【解决方案1】:

我得到 "data:application/vnd.openxmlformats-officedocument.wordprocessingml.document;base64,UEsDBB[...]" 对于 docx 和 "data:application/msword;base64,0M8R4KGxGuv[...]" 对于 doc文件。

【讨论】:

  • 在我分享的 stackblitz 上?
  • 是的,我从日志中复制了它们
猜你喜欢
  • 2015-11-06
  • 1970-01-01
  • 2016-07-10
  • 2013-08-02
  • 1970-01-01
  • 1970-01-01
  • 2017-04-18
  • 1970-01-01
  • 2023-03-24
相关资源
最近更新 更多