Android > Phone Gap >> Code Snippet Views : 4749
Rate This Article :

Image Upload using Phone gap and REST API

Code snippet mentioned in this article will explain about how to upload documents (images/videos) into server through REST services in Android APP (developed using Phone gap).

Plugin:

1.       Add “cordova-plugin-filepath” into your project to resolve the image path.

Steps:

1.       Select Image either using Camera/from Gallery.

2.       Selected image will be displayed in the UI.

3.       Post” Button to send selected/captured image to server.

HTML:

                <div class="row">

 

            <p>

                <button id="btnSelectImage" onclick="selectImageFromGallery();">Select Image From Disk</button>

 

            </p>

 

            <p>

 

                <button id="btnSelectImageFromCamera" onclick="selectImageFromCamera();">Capture image</button>

            </p>

 

            <p>

                <button id="btnClear" onclick="clearData();">Clear</button>

            </p>

 

            <button id="btnPostPhoto" onclick="uploadPhoto();">Post</button>

 

            <img style="display: none; width: 100px; height: 100px;" id="smallImage" src="" />

            <span id="imagename"></span>

 

            <progress min="0" max="100" value="0">0% complete</progress>

 

            <span id="spResult" style="color:darkblue"></span>

        </div>

 

JavaScript:

function selectImageFromCamera() {

    var popover = new CameraPopoverOptions(300, 300, 100, 100, Camera.PopoverArrowDirection.ARROW_ANY);

    var options = { quality: 49, destinationType: Camera.DestinationType.FILE_URI, sourceType: Camera.PictureSourceType.CAMERA, popoverOptions: popover };

    navigator.camera.getPicture(this.selctedFile, this.onFail, options);

}

 

function selectImageFromGallery() {

    var popover = new CameraPopoverOptions(300, 300, 100, 100, Camera.PopoverArrowDirection.ARROW_ANY);

    var options = { quality: 49, destinationType: Camera.DestinationType.FILE_URI, sourceType: navigator.camera.PictureSourceType.PHOTOLIBRARY, popoverOptions: popover };

    navigator.camera.getPicture(this.selctedFile, this.onFail, options);

}

 

function selctedFile(imageURI) {

    if (imageURI.indexOf("content") >= 0) {

        window.FilePath.resolveNativePath(imageURI, function (result) {

            imageURI = result;

 

            documentPath = imageURI;

            var image = document.getElementById("smallImage");

            image.style.display = "block";

            image.src = imageURI;

 

        }, function (error) {

            alert("File Conversion Error");

        })

    }

    else {

        //alert(imageURI);

        documentPath = imageURI;

 

        var image = document.getElementById("smallImage");

        image.style.display = "block";

        image.src = imageURI;

    }

}

 

function clearData() {

    var image = document.getElementById("smallImage");

    image.style.display = "none";

    image.src = null;

 

    documentPath = null;

}

 

function uploadPhoto() {

 

    if (documentPath == null) {

        $("#spResult").text("Document not exists!!");

    }

 

    var postUrl = "http://yourAPI.com/UpoadImageService";

 

    var fileUploadOptions = new FileUploadOptions();

    fileUploadOptions.fileKey = "CurrentFile";

    fileUploadOptions.fileName = documentPath.substr(documentPath.lastIndexOf('/') + 1);

    fileUploadOptions.mimeType = "image/png";

    fileUploadOptions.chunkedMode = true;

 

    // Additional Info to Server using JSON Object. This is Optional.

    var myObj = { "Param1": "FileUploder", "CurrentMode": 0, "Data": "", "TokenForUpload": “0000000” };

    var jsonData = JSON.stringify(myObj);

 

    fileUploadOptions.params = new Object();

    fileUploadOptions.params.CurrentData = jsonData;

 

    var fileTransfer = new FileTransfer();

 

    var progressBar = document.querySelector('progress');

    fileTransfer.onprogress = function (result) {

        var percent = (result.loaded / result.total) * 100;

        percent = Math.round(percent);

        progressBar.value = percent;

        progressBar.textContent = progressBar.value;

    };

 

    progressBar.value = 0;

    progressBar.textContent = progressBar.value;

    $("#spResult").text("");

 

    fileTransfer.upload(documentPath, postUrl, uploadPhotoWin, uploadPhotoFail, fileUploadOptions);

}

 

function uploadPhotoWin(r) {

    $("#spResult").text("Sent = " + r.bytesSent + "\n Response = " + r.response + "\n Code = " + r.responseCode + "\n");

 

    clearData();

}

 

 

function uploadPhotoFail(error) {

    switch (error.code) {

        case FileTransferError.FILE_NOT_FOUND_ERR:

            $("#spResult").text("Photo file not found");

            break;

 

        case FileTransferError.INVALID_URL_ERR:

            $("#spResult").text("Bad Photo URL");

            break;

 

        case FileTransferError.CONNECTION_ERR:

            $("#spResult").text("Connection error");

            break;

    }

 

    $("#spResult").text("An error has occurred: Code = " + error.code);

 

    clearData();

}

Note:

Please share your comments to improvise the code.

About Author
Raj Kumar
Total Posts 57
Developer in .Net!
Comment this article
Name*
Email Address* (Will not be shown on this website.)
Comments*
Enter Image Text*
   
View All Comments
Comments not posted yet!! Please post your comments on this article.
  Privacy   Terms Of Use   Contact Us
© 2016 Developerin.Net. All rights reserved.
Trademarks and Article Images mentioned in this site may belongs to Microsoft and other respective trademark owners.
Articles, Tutorials and all other content offered here is for educational purpose only and its author copyrights.