How to send multiple file and images to API?


#1

how to send my files and images to web api controller save in Database.


#2

Hi man,

You can do this easily.
If you want to send multiple images here is an example by sending images from camera to the server.

Create an array at top of your page

aImages    :  any;

Now after every photo you create you will store the image as base64 inside the array.

const options: CameraOptions = {
    sourceType: selectedSourceType,
    quality: 100,
    destinationType: this.camera.DestinationType.DATA_URL,
    correctOrientation: true,
    encodingType: this.camera.EncodingType.JPEG,
    mediaType: this.camera.MediaType.PICTURE,
    targetWidth: 1024,
    targetHeight: 1024
}

this.camera.getPicture(options).then((imageData) => {

    let picture = 'data:image/jpg;base64,' + imageData;
            
    // Push to array
    this.aImages.push({
        'image': picture
    });

}, (err) => {
    // Handle error
});

Now you can easily build up an HTTP post call and send it as data:

saveImages()
{
    var oHeaders = new Headers();
    oHeaders.append('Content-Type', 'application/x-www-form-urlencoded; charset=UTF-8');

    this.http.post('http://URL/save-images', this.aItems,{headers: oHeaders})
    .subscribe(oRes => {

        console.log('Call succesfull')

    }, (sError) => {

        console.log(sError);

    });
}

Now we go over to your PHP code.
We need to decode the base64 of the image vars.
We can do the following:

foreach($aImages as $image)
{
    // Decoded en plaatsen in de map met een unieke naam
    echo $sDecodedImg = base64_decode(preg_replace('#^data:image/\w+;base64,#i', '', $image));
}

I hope it helps you.


#3

I need also file upload like pdf, doc, excel


#4

@Arulmano
There is a Cordova plugin called file transfer it does what you need
Also ionic made a wrapper for it
Check this link



You have two options to approach your issue
Do you want to upload each file independently ?
Or do you want to upload the together?


For the first one it’s simple just iterate through the files you want to upload and upload each one independently


For the second one compress the files, then upload the compressed file


#5

have you tried this concept?what is API endpoint -I need to upload the corresponding files and view in the page and send to the server to store in DB.
I just use on MVC API controller.


#6

Yeah in an old project,
the api end point is the url that you access your api
as to save the files in the database it’s generally bad practice
depending in your use case
https://habiletechnologies.com/blog/better-saving-files-database-file-system/


#7

Hi.Can i do this using file URI. because i heard DATA.URL is much resource consuming