How to upload a file along with form data using http.post

B Faley picture B Faley · Sep 27, 2017 · Viewed 7.3k times · Source

I am submitting a form with fields like title and description using http.post and it works fine. I also allow user to use the camera to capture a photo and save it as a string in base64 format. I need to submit this photo to the server via the same POST request. How can I do this? My code so far is as the following and the server looks for the uploaded photo in a field named "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));
  }
);

Answer

Paresh Gami picture Paresh Gami · Sep 27, 2017

You have to use file transfer plugin for upload file. I am suggest to use file instead of base64. Base64 is very big string when image is capture with high resolution.

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

    );
}

You can use below function for sending data to server

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