【问题标题】:Sending multiple content type in single request在单个请求中发送多种内容类型
【发布时间】:2018-11-01 07:52:34
【问题描述】:

我正在尝试将带有附加 JSON 数据的多个文件发送到 api。该api似乎支持多种内容类型。

如何用两种内容类型形成标题 1. 多部分表单数据(用于文件) 2. application/json(用于其他json参数)

【问题讨论】:

  • 你不能。如果是 JSON,则无法指定哪个部分是多部分。不过,您没有理由不能在多部分请求中将 JSON 作为字符串值发送
  • 多部分已经是多部分。所以文件在一部分中,而 JSON 在另一部分中。

标签: json angular api header http-headers


【解决方案1】:

感谢Jack'shttps://stackoverflow.com/a/24535293/9404093 的回答,我使用不同的内容类型设置了以下内容:

uploadFile(request: FileUploadRequest, file: File): Observable<FileUploadResponse> {
    const formData: FormData = new FormData();

    formData.append('details', new Blob(
      [JSON.stringify(request)],
      { type: "application/json" }
    ));
    formData.append('file', file, file.name);
    formData.append('contentType', file.type);

    return this.http.post<FileUploadResponse>(FILES_URI, formData);
  }

通过使用 Blob,您可以将内容类型分配给 Blob 内容 (json)。

请注意,这也适用于 Java Spring 后端控制器:

@PostMapping(consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
public ResponseEntity<?> upload(@RequestPart FileUploadRequest details, @RequestPart MultipartFile file) {
    // TODO: the stuff
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-06-08
    • 1970-01-01
    • 2013-06-28
    • 1970-01-01
    • 2020-10-21
    • 1970-01-01
    相关资源
    最近更新 更多