Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 606
Bohao LI Avatar asked Oct 24 '25 20:10

Bohao LI


2 Answers

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()....
like image 64
André Pacheco Avatar answered Oct 26 '25 12:10

André Pacheco


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);
}
like image 40
Tiago Silva Avatar answered Oct 26 '25 12:10

Tiago Silva



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!