[英]How to use POST method to send form-data in Angular?
我有后端 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 上传一些图像时,我这样做:
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()....
尝试像我一样做,让我知道它是否有效。 祝你好运。
您在 post 请求( body )的正确参数中发送数据,但问题是您的对象没有被解析为正确的格式(在本例中为 'FormData' ),因为您需要声明一个新的 FormData 实例并在里面附加图像。
handleInputEvent($event) {
const image = $event.target.files[0];
const formData = new FormData();
formData.append('image', image );
this.service.recognizeFish(formData);
}
将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();
});
});
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.