4

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

2 Answers 2

7

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();
        });
    })  
}
Sign up to request clarification or add additional context in comments.

9 Comments

I want to submit the photo using POST request.
You need to post via base64 only?
No, any type defined in camera.DestinationType is acceptable (DATA_URL, FILE_URI, NATIVE_URI).
You are only capturing the image by camera. Where is your http.post method? I think you forgot to reveal your code residing in UploadBodyImagePage page.
Thanks but it's bound to only one file. What if I want to upload two or more files through the same call?
|
3

This might help : (I have used nodejs and mongodb at backend)

HTML::

<input type=“file” name=“image” accept=“image/*” (change)=“changeListener($event)”>

.ts

file: File;
changeListener($event): void {
this.file = $event.target.files[0];
this.imagesProvider.test1(this.file) // Calls test1() function in imagesProvider.ts
}

imagesProvider.ts:

test1(data){
 var options = {};
let body = new FormData();
body.append(‘image’, data);
body.append(‘desc’, “testing”);
this.http.post(“Your api endpoint”, body, options).subscribe(res => {
console.log(res);
});
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.