如何使用http.post上传文件和表单数据

Mey*_*sam 4 ionic-framework angular-file-upload ionic2 angular2-forms

我正在提交一个包含字段titledescription使用的表单,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));
  }
);
Run Code Online (Sandbox Code Playgroud)

Par*_*ami 6

您必须使用文件传输插件上传文件.我建议使用file而不是base64.当以高分辨率捕获图像时,Base64是非常大的字符串.

HTML

<button (click)="takePicture()">Take a picture</button>
Run Code Online (Sandbox Code Playgroud)

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

    );
}
Run Code Online (Sandbox Code Playgroud)

您可以使用以下功能将数据发送到服务器

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();
        });
    })  
}
Run Code Online (Sandbox Code Playgroud)