QNimate

  • CoursesVideos
  • WP PremiumPlugins
  • DemosLab
  • Home
  • QIdea
  • QTrack
Home Carbon Ads Uploading Files and Showing Progress using Intel XDK

Uploading Files and Showing Progress using Intel XDK

upload-using-intelxdk

This post is a part 28 of Intel XDK Complete Tutorial post series.

In this tutorial I will create a sample app which uploads a file to webserver using Intel XDK file upload API and also shows the percentage of file upload. I will also show how to write a backend PHP script to handle the upload.

Why not use AJAX?

We can use AJAX to upload files to server. But AJAX has some limitations. Limitations are:

  1. AJAX doesn’t provide any reporting on the percentage of the file uploaded.
  2. Mobile Internet is generally slow. We should upload only one file at a time so that we don’t overhaul Internet by multiple connection. AJAX doesn’t provide any means to report if multiple files are being uploaded at a time.

Intel XDK file upload API solves both the above issues.

Basic APP Template

Put this code in index.html file. It creates a button and progress bar.

<!DOCTYPE html>
<html>
<head>
    <title>Blank Hybrid App Project Template</title>
    <meta http-equiv="Content-type" content="text/html; charset=utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, user-scalable=no">

    <style>
        @-ms-viewport { width: 100vw ; zoom: 100% ; }                          
        @viewport { width: 100vw ; zoom: 100% ; }
        @-ms-viewport { user-zoom: fixed ; }                                    
        @viewport { user-zoom: fixed ; }
    </style>

    <script src="lib/ft/fastclick.js"></script>

    <link rel="stylesheet" href="css/app.css">
</head>
<body>
    <button onclick="upload_to_server();">Create and Upload Text File</button>
    <progress value="0" min="0" max="100" id="progress"></progress>
   
    <script src="intelxdk.js"></script>        
    <script src="cordova.js"></script>          
    <script src="xhr.js"></script>              

    <script src="js/app.js"></script>
    <script src="js/init-app.js"></script>
    <script src="js/init-dev.js"></script>
</body>
</html>

Including Intel XDK File Upload API

Before we proceed with using Intel XDK File upload API we need to make sure you include Intel XDK File plugin in your app.

Screen Shot 2014-11-24 at 7.12.36 pm

Creating a Text File

Let’s create a text file using Cordova File System API. We are going to uploading this created text file. You can also upload a existing file.

        function upload_to_server()
        {
            requestFileSystem(LocalFileSystem.PERSISTENT, 0, onSuccess, onError);
        }
       
        function onSuccess(fileSystem)
        {  
            var directoryEntry = fileSystem.root;      
            directoryEntry.getFile("readme.txt", {create: true, exclusive: false}, function(fileEntry){
                fileEntry.createWriter(function(writer){
                    writer.write("This is the text inside readme file");
                   
                    var pathOfFile = fileEntry.fullPath;
                   
                }, function(error){
                    alert("Error occurred while writing to file. Error code is: " + error.code);
                });
            }, function(error){
                alert("Error occurred while getting a pointer to file. Error code is: " + error.code);
            });
        }
       
        function onError(evt)
        {
            alert("Error occurred during request to file system pointer. Error code is: " + evt.code);
        }

Uploading File and Showing Progress

We are going to use uploadToServer function of File Upload API to upload the file. Here is the code to upload it to server.

First parameter of the function should be absolute path to the file. And second parameter should point to the web server script which is going to handle the upload.

    intel.xdk.file.uploadToServer(pathOfFile,"http://labs.qnimate.com/intelxdk-upload/upload.php", "", "text/plain", "updateUploadProgress");

    function updateUploadProgress(bytesSent,totalBytes)
    {
       if(totalBytes>0)
            currentProgress=(bytesSent/totalBytes)*100;
        document.getElementById("progress").setAttribute("value", currentProgress);
    }

    document.addEventListener("intel.xdk.file.upload.busy",uploadBusy);
    document.addEventListener("intel.xdk.file.upload",uploadComplete);
    document.addEventListener("intel.xdk.file.upload.cancel",uploadCancelled);

    function uploadBusy(evt)
    {
       alert("Sorry, a file is already being uploaded");
    }

    function uploadComplete(evt)
    {
       if(evt.success==true)
       {
          alert("File "+evt.localURL+" was uploaded");
       }
       else {
          alert("Error uploading file "+evt.message);
       }
    }

    function uploadCancelled(evt)
    {
        alert("File upload was cancelled "+evt.localURL);
    }

Complete APP Code

Here is the combination of all the above code

<!DOCTYPE html>
<html>
<head>
    <title>Blank Hybrid App Project Template</title>
    <meta http-equiv="Content-type" content="text/html; charset=utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, user-scalable=no">

    <style>
        @-ms-viewport { width: 100vw ; zoom: 100% ; }                          
        @viewport { width: 100vw ; zoom: 100% ; }
        @-ms-viewport { user-zoom: fixed ; }                                    
        @viewport { user-zoom: fixed ; }
    </style>

    <script src="lib/ft/fastclick.js"></script>

    <link rel="stylesheet" href="css/app.css">
</head>
<body>
    <button onclick="upload_to_server();">Create and Upload Text File</button>
    <progress value="0" min="0" max="100" id="progress"></progress>
   
    <script src="intelxdk.js"></script>        
    <script src="cordova.js"></script>          
    <script src="xhr.js"></script>              

    <script src="js/app.js"></script>
    <script src="js/init-app.js"></script>
    <script src="js/init-dev.js"></script>
   
    <script>
       
        function upload_to_server()
        {
            requestFileSystem(LocalFileSystem.PERSISTENT, 0, onSuccess, onError);
        }
       
        function onSuccess(fileSystem)
        {  
            var directoryEntry = fileSystem.root;      
            directoryEntry.getFile("readme.txt", {create: true, exclusive: false}, function(fileEntry){
                fileEntry.createWriter(function(writer){
                    writer.write("This is the text inside readme file");
                   
                    var pathOfFile = fileEntry.fullPath;
        intel.xdk.file.uploadToServer(pathOfFile,"http://labs.qnimate.com/intelxdk-upload/upload.php", "", "text/plain", "updateUploadProgress");
                   
                }, function(error){
                    alert("Error occurred while writing to file. Error code is: " + error.code);
                });
            }, function(error){
                alert("Error occurred while getting a pointer to file. Error code is: " + error.code);
            });
        }
       
        function onError(evt)
        {
            alert("Error occurred during request to file system pointer. Error code is: " + evt.code);
        }
       
       

    function updateUploadProgress(bytesSent,totalBytes)
    {
       if(totalBytes>0)
            currentProgress=(bytesSent/totalBytes)*100;
        document.getElementById("progress").setAttribute("value", currentProgress);
    }

    document.addEventListener("intel.xdk.file.upload.busy",uploadBusy);
    document.addEventListener("intel.xdk.file.upload",uploadComplete);
    document.addEventListener("intel.xdk.file.upload.cancel",uploadCancelled);

    function uploadBusy(evt)
    {
       alert("Sorry, a file is already being uploaded");
    }

    function uploadComplete(evt)
    {
       if(evt.success==true)
       {
          alert("File "+evt.localURL+" was uploaded");
       }
       else {
          alert("Error uploading file "+evt.message);
       }
    }

    function uploadCancelled(evt)
    {
        alert("File upload was cancelled "+evt.localURL);
    }      
    </script>
</body>
</html>

Handling Upload Using PHP

Here is the code to handle the uploaded file using PHP. Here we move the uploaded file to a uploads folder.

<?php
    move_uploaded_file($_FILES["Filedata"]["tmp_name"], "uploads/" . $_FILES["Filedata"]["name"]);
?>

Conclusion

If your app has uploading file functionality then its always better to display upload progress. This provides a great user experience.

Nov 24, 2014Narayan Prusty
Working with File System using Intel XDKAdding Custom Content to Printed Web Pages
Comments: 12
  1. Friv
    6 years ago

    Could you please tell me a very simple method to transfer image file to the server using intel xdk.

    ReplyCancel
  2. Eliezer
    6 years ago

    Good morning,

    I hope you can help me, I’m developing an enterprise application that work. is made in HTML, PHP, JavaScript as the design for a web environment, only the android application made XDK place it in an

    <

    iframe>. It works well hsta the point where I have to upload some files to the server from the browser I can upload multiple files at once, but from the android application I can only upload one at a time.

    I could help’ll be very grateful.

    sorry for my English.

    Thank you!

    ReplyCancel
  3. Ramon Guzman
    7 years ago

    Hi, do you know why doesn’t work on iOS?
    Specific on the part when I try to upload the picture :/

    ReplyCancel
  4. Tiago
    7 years ago

    Error

    Uncaught ReferenceError: requestFileSystem is not defined

    ReplyCancel
  5. Ali Jaffar
    7 years ago

    Interesting tutorial series, but I find this particular section to no longer work.

    ReplyCancel
  6. cesar barahona
    7 years ago

    Hi,

    Help me please : In “Uploading Files and Showing Progress using Intel XDK”, He hands me the following error.

    Error occurred while getting a pointer to file. Error code is: 1.

    To which it should be?
    Thanks

    ReplyCancel
  7. Marco Gonzalez
    7 years ago

    Excellent post. Could you share with us the source code of the project. thank

    ReplyCancel
  8. Ashwini
    7 years ago

    After calling uploadToServer() its giving can’t find the file error..

    ReplyCancel
  9. Wee
    8 years ago

    is that the only code in the php file? no other?

    ReplyCancel
    • Narayan Prusty
      8 years ago

      yup

      ReplyCancel
  10. Adrian
    8 years ago

    requestFileSystem function is not available on Intel XDK App starter. Please help.

    ReplyCancel
    • Narayan Prusty
      8 years ago

      App Starter is only used to design apps. You need to write code on Intel XDK software to implement functionality.

      ReplyCancel

Leave a Reply Cancel reply

To create code blocks or other preformatted text, indent by four spaces:

    This will be displayed in a monospaced font. The first four
    spaces will be stripped off, but all other whitespace
    will be preserved.
    
    Markdown is turned off in code blocks:
     [This is not a link](http://example.com)

To create not a block, but an inline code span, use backticks:

Here is some inline `code`.

For more help see http://daringfireball.net/projects/markdown/syntax

Narayan Prusty

I am a software engineer specialising in Blockchain, DevOps and Go/JavaScript. This is my personal blog where I write about things that I learn and feel interesting to share.

Image8 years ago 13 Comments Cordova
Share this
0
GooglePlus
0
Facebook
0
Twitter
0
Linkedin
  • Why not use AJAX?
  • Basic APP Template
  • Including Intel XDK File Upload API
  • Creating a Text File
  • Uploading File and Showing Progress
  • Complete APP Code
  • Handling Upload Using PHP
  • Conclusion
Related Articles
  • Create a Camera App using Intel XDK
  • Create a Barcode Scanner Application using Intel XDK and PHP
  • Downloading Files and Showing Progress using Intel XDK
  • Create a Feed Reader App using Intel XDK
  • Intel XDK Geolocation Tutorial
Our Sponsor
My Books

2014 - 2015 © QNimate
All tutorials MIT license