当前请求不是angular 11中的多部分请求

3pvhb19x  于 2021-09-23  发布在  Java
关注(0)|答案(1)|浏览(271)

我正在尝试上传Angular 图像。
我执行以下步骤:
在服务中,我使用以下设置:

postFormDataToServerMultiPart(action: string, formData) {
    var headerss = new HttpHeaders({
      "Content-Type": "multipart/form-data"
    });

    return this.http
      .post(HttpService.apiUrl + action, formData, { headers: headerss })
      .pipe(map((response: any) => response));
  }

标题包含: "Content-Type": "multipart/form-data" 在component.ts中:

var formData = new FormData();
          formData.append("file", this.imageForm.get("profile").value);

          if (this.Image) {
            this.httpService
              .postFormDataToServerMultiPart(
                "api/upload/driver_image?id=" + this.employeeId,
                formData
              )
              .subscribe((resp) => {
                console.log("edit", resp);
                if (resp.status == "SUCCESS") {
                  var dialogRef = this.dialog.open(DisplayPopupComponent, {
                    data: {
                      title: "Driver Updated Successfully!",
                    },

    ............

我收到这个错误:

error: "Internal Server Error"
message: "Current request is not a multipart request"
path: "/api/upload/driver_image"
status: 500
timestamp: "2021-07-09T13:45:23.443+0000"

我做错了什么?
小姐怎么了?

ttisahbt

ttisahbt1#

此操作失败,因为您正在手动设置 Content-Type 标题,而不是让浏览器为您执行此操作。如果您按原样使用代码发送该请求,请进入开发工具并查看请求头。您将看到:

Content-Type: multipart/form-data

这实际上是不完整的,因为您缺少边界。只需删除手动标题即可解决此问题,因为浏览器将正确设置 Content-Type 并添加边界。

postFormDataToServerMultiPart(action: string, formData) {
    return this.http
      .post(HttpService.apiUrl + action, formData)
      .pipe(map((response: any) => response));
  }

发送此请求后,再次检查dev工具中的请求头,您将看到如下内容:

Content-Type: multipart/form-data; boundary=----12345678901234567890

有关更多信息,请参阅https://developer.mozilla.org/en-us/docs/web/http/headers/content-type#directives

相关问题