我想将多部分表单数据上传到restapi,在Postman客户端上请求时api正常工作。
这是我的代码:
takePhoto() {
const options: CameraOptions = {
quality: 100,
allowEdit: true,
targetWidth: 200,
targetHeight: 200,
saveToPhotoAlbum: true,
encodingType: this.camera.EncodingType.JPEG,
mediaType: this.camera.MediaType.PICTURE
};
this.camera.getPicture(options).then(image => {
console.log('Image URI: ' + image);
this.image_File = image;
this.imgfile = this.imageURI;
console.log(JSON.stringify(this.imageURI));
this.avatar = image.slice(7);
this.imgfile = this.avatar;
}, error => {
console.log('Error: ' + error);
});
}
为上传文件,我定义了一个函数:
console.log("begin to upload ");
let link = rootUrl+"merchant/merchant-image";
let data = new FormData();
// var blob = new Blob([this.image_File], { type: "image/jpg" });
data.append('merchantId', '2');
data.append('merchantImage',this.imgfile);
console.log(data);
this.http.post(link, data,{
headers:{
"Accept-Language":this.lang,
//'enctype': 'multipart/form-data',
// 'Content-Type': 'multipart/form-data',
}
}).subscribe(data2 => {
console.log("data Successful "+ data2);
}, error => {
console.log("Oooops! error "+ JSON.stringify(error));
});
来自服务器的响应:
{
"headers": {
"normalizedNames": {},
"lazyUpdate": null
},
"status": 400,
"statusText": "OK",
"url": "http://xxxxxxxxxxx/merchant/merchant-image",
"ok": false,
"name": "HttpErrorResponse",
"message": "Http failure response for http://xxxxxxxxxxxxx/merchant/merchant-image: 400 OK",
"error": {
"timestamp": "2018-08-14T10:13:14.693+0000",
"status": 400,
"error": "Bad Request",
"message": "Required request part 'merchantImage' is not present",
"path": "/api/v1/merchant/merchant-image"
}
}