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

问题描述 投票:-1回答:3

我有一个后端api接受一个POST方法,图像为form-data,像这样,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

angular form-data
3个回答
1
投票

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

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()....

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


0
投票

您正在使用post请求(正文)的正确paremeter发送数据,但问题是您的对象未被解析为正确的格式(在本例中为'FormData'),因为您需要声明FormData的新实例并将图像附加到里面。

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

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();
        });
    });
  }
© www.soinside.com 2019 - 2024. All rights reserved.