如何使用POST方法在Angular中发送表单数据?

时间:2019-02-14 15:11:39

标签: angular form-data

我有一个后端api,它可以将POST方法的图像作为表单数据,就像这样, enter image description here

使用上述邮递员时,一切正常。 但是当我想在Angular中执行此操作时,它不起作用。 在我的html文件中:

<input type="file" (change)="handleInputEvent($event)"/>

在我的.ts文件中:

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

}

我的服务文件(使用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});
  }
  ....

后端开发人员(使用Flask开发了后端)给我以下代码:

@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!'})

他还告诉我,响应中的“ code”属性为0时表示错误,为1时表示没有错误。 当我在浏览器中测试Angular应用程序时,出现以下错误: enter image description here

3 个答案:

答案 0 :(得分:1)

当我使用角度上传一些图像时,我会这样做:

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

    form.append('image', img);

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

  }

,效果很好。 因此,我认为您代码中的问题是您没有在此处将formData传递给post方法:

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

尝试像我一样做,让我知道它是否有效。 祝你好运。

答案 1 :(得分:0)

您正在以发布请求(主体)的正确参数发送数据,但是问题是您的对象没有被解析为正确的格式(在这种情况下为'FormData'),因此您需要声明一个新的实例的FormData并将图像附加到其中。

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

答案 2 :(得分:0)

FormData直接传递给您的post方法。

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