简体   繁体   中英

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 ?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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