【问题标题】:How to use POST method to send form-data in Angular?如何使用 POST 方法在 Angular 中发送表单数据?
【发布时间】:2021-11-14 16:10:16
【问题描述】:

我有后端 API,它接受带有图像表单数据的 POST 方法,如下所示,

当像上面那样使用 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 应用程序时,我遇到了这个错误:

【问题讨论】:

    标签: angular form-data


    【解决方案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()....
    

    【讨论】:

    • 事实上,即使我将 formData 作为第二个参数传递给该方法,它也不起作用。
    • 不要将标头传递给 http,只传递 url 和 formData。它应该可以解决您的问题
    • 不要将标头传递给 http,只传递 url 和 formData。它应该可以解决您的问题
    • 我真的不知道为什么,但这确实解决了我的问题!非常感谢。
    • @AndréPacheco 如果我有图像以及其他一些关键值该怎么办。
    【解决方案2】:

    您正在以正确的 post 请求 (body) 参数发送数据,但问题是您的对象没有被解析为正确的格式(在本例中为“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();
    【解决方案3】:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-10-09
      • 2012-11-20
      • 2014-07-19
      • 2012-09-10
      • 1970-01-01
      • 2012-05-13
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多