The current request is not a multipart request in angular 11

Viewed 101

i am trying to upload image in angular.

I do this step:

In service i use this settings:

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

headers contain : "Content-Type": "multipart/form-data"

In 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!",
                    },

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

I receive this error :

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"

what i do wrong?

What in miss?

1 Answers

This is failing because you are manually setting the Content-Type header instead of letting the browser do this for you. If you send that request with your code as-is, go into the dev tools and check out the request headers. You'll see:

Content-Type: multipart/form-data

This is actually not complete, as you are missing the boundary. Simply removing the manual headers should fix this because the browser will properly set the Content-Type and add the boundaries.

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

After sending this request, check the dev tools again for the request headers and you'll see something like:

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

For more information see https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Type#directives

Related