繁体   English   中英

将多部分/表单数据发布到端点

[英]Post multipart/form-data to endpoint

我正在尝试为角度为6的excel文件创建一个上传表单。我实现了一个文件选择器,我想使用该文件选择器将excel文件上传(发布)到某个期望“ MULTIPART_FORM_DATA”的端点。 现在,我了解到您不应该在头版本中为高于5的角版本设置内容类型,但是如果我在头中不包含内容类型,则角应用程序会自动将其设置为“ application / vnd.openxmlformats-officedocument.spreadsheetml “ .sheet”,服务器不会期望它,因此会导致“错误请求”。 那么,如何为角度为6的multipart / form-data实现有效的“ post”?

端点看起来像这样:

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

角度分量看起来像这样:

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);

}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM