Search code examples
visual-studioweb-servicescordovaapache-cordova

Cordova - Insert to web page's database


I'm developing an app using Apache Cordova for Visual Studio. The purpose of this app is to take a picture using the phone and upload this picture alongside with some other user input data to our company's webpage, that uses a SQL-server Database to store it's data.

So, the question is: How can I insert data to this database so I can show it on the webpage, considering that the app will be used outside of our network? So it can't be a local connection to our database!


Solution

  • var pictureSource;
     var destinationType;
    document.addEventListener("deviceready", onDeviceReady, false);
    

    On device ready

    function onDeviceReady() {
        pictureSource = navigator.camera.PictureSourceType;
        destinationType = navigator.camera.DestinationType;
    }
    

    Clean Up

    function clearCache() {
        navigator.camera.cleanup();
    }
    
    var retries = 0;
    

    Upload photo taken from camera

    function onCapturePhoto(fileURI) {
    document.getElementById('MyElement').innerHTML = 'Uploading....';
        var win = function (r) {
        clearCache();
        retries = 0;
        document.getElementById('MyElement').innerHTML = '';
        alert('Image Uploaded! Successfully');
    };
    
    var fail = function (error) {
        if (retries === 0) {
            retries++;
            setTimeout(function () {
                document.getElementById('MyElement').innerHTML = '';
                onCapturePhoto(fileURI);
            }, 1000);
        } else {
            retries = 0;
            clearCache();
            document.getElementById('MyElement').innerHTML = '';
            alert('Something went wrong..Try Again');
        }
    };
    var options = new FileUploadOptions();
    options.fileKey = "file";
    options.fileName = fileURI.substr(fileURI.lastIndexOf('/') + 1);
    options.mimeType = "image/jpeg";
    options.params = {};
    var ft = new FileTransfer();
    ft.upload(fileURI, encodeURI("http://yourserver.com/phpfile.php"), win, fail, options);
    }
    
       function onFail(message) {
        alert(message);
        }
    

    Function To Call The Camera

    <a href="#" onclick="capturePhoto();">Take Picture</a>

       function capturePhoto() {
            navigator.camera.getPicture(onCapturePhoto, onFail, {
            quality: 100,
            destinationType: destinationType.FILE_URI,
            sourceType: Camera.PictureSourceType.CAMERA,
            encodingType: Camera.EncodingType.JPEG
        });
        }
    

    Php part

                 <?php
                 $sourcePath = $_FILES['file']['tmp_name'];
                 $targetPath = "images/".$_FILES['file']['name']; // save uploaded image to images folder
                 move_uploaded_file($sourcePath,$targetPath) ;
                 ?>