Angular 7正确上传doc / docx文件

问题描述

我在上传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

解决方法

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