[英]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.