Bohao LI
Bohao LI

Reputation: 2713

How to use POST method to send form-data in Angular?

I have backend API which accepts a POST method with an image form-data, like this, enter image description here

When using Postman like above, everything works well. But when I want to do this in Angular, it does not work.

<!-- html template file -->
<input type="file" (change)="handleInputEvent($event)"/>
import {Component, OnInit} from '@angular/core';
import {MyDearFishService} from '../../my-dear-fish.service';

@Component({
  selector: 'app-upload',
  templateUrl: './upload.component.html',
  styleUrls: ['./upload.component.scss']
})
export class UploadComponent implements OnInit {

  constructor(public service: MyDearFishService) {
  }

  ngOnInit() {
  }

  arrayOne(n: number): any[] {
    return Array(n);
  }

  handleInputEvent($event) {

    const image = $event.target.files[0];
    this.service.recognizeFish(image);
  }

}
// My service file (using HttpClient):
const rootUrl = 'https://...../api';

public recognizeFish(image: File): Promise<any> {
  return new Promise((resolve, reject) => {

    const formData = new FormData();
    formData.append('image', image);

    this.post('/image/identification', formData)
      .toPromise()
      .then(res => {
        if (res['code'] === 0) {
          console.log('=====================================');
          console.log('Recognition failed, cause = ', res);
          console.log('=====================================');
        } else {
          console.log('=====================================');
          console.log('Recognition succeeded, res = ', res);
          console.log('=====================================');
        }
        resolve();
      })
      .catch(cause => {
        console.log('=====================================');
        console.log('Recognition failed, cause = ', cause);
        console.log('=====================================');
        reject();
      });
    ;
  });
}

private getOptions(headers?: HttpHeaders, params?): HttpHeaders {
  if (!headers) {
    headers = new HttpHeaders().append('Content-Type', 'application/x-www-form-urlencoded');
  }
  return headers;
}

post(route: string, body: any, headers?: HttpHeaders): Observable<any> {
  headers = this.getOptions(headers);
  return this.http.post(rootUrl + route, body, {headers});
}

The backend developer (who developed the back-end using Flask) give me this code:

@main.route("/image/identification", methods=['POST'])
@login_required
def identification():
    image_file = request.files.get('image', default=None)
    if image_file:
        picture_fn = save_picture(image_file, 2)
        return identif(picture_fn)
    else:
        return jsonify({'code':0, 'message':'image file error!'})

And he also told me that when the "code" property in the response is 0, it means error, when it is 1, it means no error. When I test my Angular app in the browser, I've got this error: enter image description here

Upvotes: 4

Views: 14364

Answers (3)

Andr&#233; Pacheco
Andr&#233; Pacheco

Reputation: 1885

When I upload some image using angular, I do this:

public uploadImage (img: File): Observable<any> {
    const form = new FormData;

    form.append('image', img);

    return this.http.post(`${URL_API}/api/imagem/upload`, form);

  }

and it works fine. So, I think the problem in your code is that you're not passing the formData to your post method here:

this.post('/image/identification', {files: {image: image}})
        .toPromise()....

Upvotes: 6

Sudarshana Dayananda
Sudarshana Dayananda

Reputation: 5255

Pass FormData directly to your post method.

  public recognizeFish(image: File): Promise<any> {
    return new Promise((resolve, reject) => {

      let formData = new FormData();
      formData.append('image', image);

      this.post('/image/identification', formData)
        .toPromise()
        .then(res => {
          console.log('Recognition okay, res = ', res);
          resolve();
        })
        .catch(cause => {
          console.log('Recognition failed, cause = ', cause);
          reject();
        });
    });
  }

Upvotes: 0

Tiago Silva
Tiago Silva

Reputation: 2349

You are sending the data in the correct paremeter of the post request ( body ) but the problem is that your object is not getting parsed as the correct format ( in this case 'FormData' ) for that you need to declare a new instance of FormData and append the image inside.

 handleInputEvent($event) {
     const image = $event.target.files[0];
     const formData = new FormData();
     formData.append('image', image );
     this.service.recognizeFish(formData);
}

Upvotes: 1

Related Questions