如何在 Angular 中通过 REST API 上传 CSV 文件?

Vic*_*ona 3 javascript csv api file-upload angular

在我的 html 中,我有:

 name="file" type="file"
 accept=".csv"
Run Code Online (Sandbox Code Playgroud)

在 ts: 我得到文件 - $event.target.files.item(0);

然后我将它传递给服务

  uploadCSVFile( file) {
    const uploadedFile = new FormData();
    uploadedFile.append( 'file', file, file.name);
    const url = `MyURL`;
    return this.http.post(url, uploadedFile);
  }
Run Code Online (Sandbox Code Playgroud)

问题是它说文件必须有一个 contentType text/csv 但是当我添加标题时 -

{headers:  new HttpHeaders().append('Content-Type', 'text/csv')}
Run Code Online (Sandbox Code Playgroud)

抱怨请求不是多部分的。

Vic*_*ona 9

该问题与 MIME 类型不匹配有关。跨平台的文件 MIME 类型无法识别为相同。OSX 中的 .csv 文件被识别为 text/csv,而在 Windows 中它被识别为 application/vnd.ms-excel。

这是解决方案 - 更改行:

 uploadedFile.append( 'file', new Blob([file], { type: 'text/csv' }), file.name);
Run Code Online (Sandbox Code Playgroud)