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

3
我有一个后端API,它接受一个带有图像表单数据的POST方法,就像这样: enter image description here 当使用Postman时,一切正常。但是当我想在Angular中执行此操作时,它不起作用。
<!-- 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});
}

后端开发人员(使用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个回答

6

当我使用 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()....

事实上,即使我将formData作为第二个参数传递给该方法,它也无法正常工作。 - Bohao LI
不要传递头信息,只需将URL和formData传递给http即可解决您的问题。 - André Pacheco
1
不要传递头信息,只需将URL和formData传递给http即可解决您的问题。 - André Pacheco
1
我不太清楚为什么,但这确实解决了我的问题!非常感谢。 - Bohao LI
@AndréPacheco 如果我有一张图片和其他一些键值,该怎么办? - Sanjay Sahani

0
你正在将数据以正确的参数(body)发送到post请求中,但问题是你的对象没有被解析为正确的格式(在本例中为'FormData'),因此你需要声明一个新的FormData实例并将图像附加在内。
 handleInputEvent($event) {
     const image = $event.target.files[0];
     const formData = new FormData();
     formData.append('image', image );
     this.service.recognizeFish(formData);
}

它返回了一个HTTP请求错误,还是您的请求甚至没有执行?如果没有执行,只需添加到this.service.recognizeFish(formData).subscribe(); - Tiago Silva

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接