Kakashi
Kakashi

Reputation: 309

How can I send a file using http POST request as a formData?

I'm using swagger 2.0 to document my API. I defined a resource /getsize as shows the next code snippet:

    post:
      operationId: users.getSize
      tags:
        - Users
      summary: Measure your body
      description: import a photo
      consumes:
         - multipart/form-data
      parameters:
        - in: formData
          name: image1
          type: file
          required: true
        - in: path
          name: height
          type: number
          required: true

When I try to send the request from the sawgger ui I get the expected result. But, the problem occurs when I try to access this resource using angluar component, here a code snippet of the component.ts file:

onSubmit() {
    const formData = new FormData();
    formData.append('image1', this.image);
    console.log(formData.getAll);
    console.log(this.image);
    this.http.post(endpoint,formData);
    .subscribe(res => {
        console.log(res);
        alert('SUCCESS !!');
      })
}

The server response is:

error:
detail: "Missing formdata parameter 'image1'"
status: 400
title: "Bad Request"
type: "about:blank"

Any suggestions ?

Upvotes: 0

Views: 724

Answers (1)

RajuPedda
RajuPedda

Reputation: 3379

You can do this using URLSearchParams as the body of the request and angular will automatically set the content type to application/x-www-form-urlencoded and encode the body properly.

This post explained the answer in detail

Upvotes: 1

Related Questions