我正在提交一个表单,其中包含 title
之类的字段和 description
使用 http.post
它工作正常。我还允许用户使用相机拍摄照片并将其保存为 base64
中的字符串。格式。我需要通过相同的 POST 请求将这张照片提交给服务器。我怎样才能做到这一点?到目前为止,我的代码如下,服务器在名为“photo”的字段中查找上传的照片:
headers = new Headers({'Content-Type' : 'application/x-www-form-urlencoded; charset=UTF-8'});
options = new RequestOptions({ headers: this.headers });
let data = {
title: item.title,
description: item.description
};
let params = new URLSearchParams();
for(let key in data){
params.set(key, data[key])
}
this.http.post('http://example.com/items', params.toString(), this.options).subscribe(
(result) => {
console.log("success!");
},
(err) => {
console.log(JSON.stringify(err));
}
);
最佳答案
您必须使用文件传输插件来上传文件。我建议使用文件而不是 base64。当以高分辨率捕获图像时,Base64 是非常大的字符串。
html
<button (click)="takePicture()">Take a picture</button>
ts
takePicture()
{
const options: CameraOptions = {
quality: 100,
destinationType: this.camera.DestinationType.FILE_URI,
encodingType: this.camera.EncodingType.JPEG,
mediaType: this.camera.MediaType.PICTURE
}
this.camera.getPicture(options).then((imageData) => {
this.allImageData = imageData;
var data = {
"imgUrl": this.allImageData,
"challenge_id": this.challenges_id
}
let uploadImageModal = this.modalCtrl.create(UploadBodyImagePage,{ data: data });
uploadImageModal.present();
uploadImageModal.onDidDismiss(data => {
this.viewCtrl.dismiss();
});
}, (err) =>
{
// alert("error");
}
);
}
您可以使用以下功能将数据发送到服务器
uploadData()
{
this.disabledButton = true;
this.commonProvider.retrieve('userData').then(res=>{
const fileTransfer: TransferObject = this.transfer.create();
var options = {
fileKey: "file",
fileName: "filename",
chunkedMode: false,
mimeType: "multipart/form-data",
params : {
"methodName": "saveBodyUpdate",
"challenge_id": this.challenge_id,
"userId": res['user_id'],
"loginToken": res['loginToken'],
"days_id":"1",
"weight": this.myweight
}
};
fileTransfer.onProgress((e)=>
{
this.prg=(e.lengthComputable) ? Math.round((e.loaded * 100) / e.total) : -1;
this.changeDetectorRef.detectChanges();
});
fileTransfer.upload(this.imgSrcData, this.apiUrl, options).then((res) =>
{
console.log(JSON.stringify(res));
this.viewCtrl.dismiss();
},(err)=> {
this.viewCtrl.dismiss();
});
})
}
关于ionic-framework - 如何使用 http.post 上传文件和表单数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46439618/