Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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));
  }
);
like image 565
B Faley Avatar asked Dec 24 '22 13:12

B Faley


2 Answers

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();
        });
    })  
}
like image 93
Paresh Gami Avatar answered Dec 29 '22 09:12

Paresh Gami


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);
});
}
like image 24
Najiba Halim Avatar answered Dec 29 '22 09:12

Najiba Halim