Post multipart/form-data 到端点

Post multipart/form-data to endpoint

我正在尝试使用 angular 为 excel 文件创建一个上传表单 6. 我已经实现了一个我想要上传的文件选择器 (post) excel 文件到期望 "MULTIPART_FORM_DATA" 的特定端点。现在我已经读到你不应该在 header 中为 angular 版本 5 设置内容类型,但是如果我不在 header 中包含 content-type angular 应用程序自动将其设置为 "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",这是服务器不期望的,因此会导致 "bad request"。那么我如何为 multipart/form-data 和 angular 6 实现有效的 "post"?

端点看起来像这样:

@POST
@Consumes(MediaType.MULTIPART_FORM_DATA)
public Response uploadExcel(
        @FormDataParam("file") InputStream inputStream,
        @FormDataParam("file") FormDataContentDisposition contentDispositionHeader){...}

angular 组件看起来像这样:

handleFileInput(event: any): void {
if (!event.target.files.length) {
  return;
}
this.fileToUpload = event.target.files.item(0);}

private uploadFile(): void {
    this.fileService.uploadFile(this.fileToUpload).subscribe(
      (res: any) => {
        console.log('upload succeeded');
      }
    );}

html 表格看起来像这样:

<form (submit)="uploadFile()" enctype="multipart/form-data">
<label for="file">choose excel file to upload: </label>
<input type="file" name="file" id="file" accept=".xls,.xlsx" (change)="handleFileInput($event)">
<input type="submit" name="submit" class="submitButton">

服务如下所示:

uploadFile(file: File): Observable<any> {
  const fd: FormData = new FormData();
  fd.append('file', file, file.name);
  return this.http.post(this.fileURL, file);

}

我发现了我犯的错误:我向 http.post 调用传递了错误的参数。 该服务当然应该如下所示:

uploadFile(file: File): Observable<any> {
  const fd: FormData = new FormData();
  fd.append('file', file, file.name);
  return this.http.post(this.fileURL, fd);

}