Install the App?

Uploading files from your Application

DESCRIPTION This application demonstrates how to upload files from your ZnetDK for Mobile App.

The file upload mechanism is based on the <input> element declared with type="file" and the multiple property. An event handler is attached to the update events to display the selected files through the FileList Web API


PREREQUISITE The ZnetDK for Mobile Starter Application is installed and configured (go to the Get Started page and follow the given procedure).

STEPS Only three steps are required:
  • Step 1: Coding of the view that displays the form for selecting files to upload,
  • Step 2: Coding of the controller that processes the loaded files,
  • Step 3: Adding a new item to the App's navigation menu.

DEMONSTRATION See live demo....

Step 1 - Coding the view uploadview.php

The view uploadview.php must be installed into the INSTALL_DIR/applications/default/app/view/ folder.

About de HTML code:

  • The <form> element is declared with data-zdk-submit="uploadctrl:upload" to connect it to the uploadctrl controller and the upload action (see step 2 for detail on the controller action).
  • Within the form, the <input type="file"> element is named files[] (please note the square brackets) and the multiple property is set to allow multiple file selection. This input element is hidden by setting the CSS style to opacity:0
  • The file selection dialog is displayed when clicking the Select files... button.
  • Selected files are displayed into the <div class="selected"> element. The <p class="no-selection> paragraph is displayed when no file is selected.
  • A File tag entry field is also added to the form in order to associate in option, a tag to the file selection.
  • User submits the form by clicking the Upload button.

About the JavaScript code:

  • Calling the znetdkMobile.form.make() method enables data form transfer in AJAX to the specified controller action specified through the data-zdk-submit attribute. The submit callback function is implemented to customize the display of the response returned by the controller action.
  • When the Selected files... button is clicked, a click event is triggered on the input of type file to show the file selection dialog.
  • A event handler is declared for the update events issued by the input of type file when the file selection dialog is closed.
    The file selection is obtained via the this object within the event handler that has the files property which is of type FileList.
    If no file is selected, the message No file selected is displayed.
    Otherwise, the selected file names are added into the <div class="selected"> element and styled for display.

View uploadview.php

<form id="znetdkm-upload-demo" class="w3-theme-light" novalidate data-zdk-submit="uploadctrl:upload">
    <div class="w3-section">
        <label class="zdk-required"><b>Files to upload</b></label>
        <input class="upload w3-hide" type="file" name="files[]" multiple required style="opacity:0;position:absolute">
        <button class="upload w3-button w3-block w3-theme-action w3-margin-bottom" type="button"><i class="fa fa-folder-open-o fa-lg"></i> Select files...</button>
        <div class="w3-section">
            <p class="no-selection w3-text-red"><i class="fa fa-exclamation-circle"></i> No file selected.</p>
            <div class="selected"></div>
        </div>
        <label><b>File Tag</b></label>
        <input class="w3-input w3-border" type="text" name="file_tag" placeholder="Picture, Music, PDF document, ...">
        <button class="w3-button w3-block w3-green w3-section w3-padding" type="submit"><i class="fa fa-upload fa-lg"></i> Upload</button>
    </div>
</form>
<script>
    let uploadForm = znetdkMobile.form.make('#znetdkm-upload-demo', function(response) {
        if (response.success) {
            znetdkMobile.messages.removeAll();
            znetdkMobile.messages.add('info', response.summary, response.msg, false);
            return false;
        }
    });
    $('#znetdkm-upload-demo button.upload').on('click', function(){
        var fileInput = $('#znetdkm-upload-demo input.upload');
        fileInput.trigger('click');
        fileInput.off('change').one('change', function(){
            const selectedFiles = this.files,
                noSelectionEl = $('#znetdkm-upload-demo .no-selection'),
                selectionContainer = $('#znetdkm-upload-demo .selected');
            if (selectedFiles.length === 0) {
                noSelectionEl.removeClass('w3-hide');
                selectionContainer.empty();
                selectionContainer.addClass('w3-hide');
                return false;
            }
            noSelectionEl.addClass('w3-hide');
            selectionContainer.removeClass('w3-hide');
            for (let i = 0; i < selectedFiles.length; i++) {
                currentFile = selectedFiles.item(i);
                selectionContainer.append('<span class="w3-tag w3-round-large w3-theme-l3 w3-margin-right"><i class="fa fa-file-o"></i> ' + currentFile.name + '</span>');
            }
            // Form error message is hidden
            uploadForm.hideError();
        });
    });
</script>
HTM5 JS

Step 2 - Coding the controller uploadctrl.php

The PHP script uploadctrl.php processes the data transmited on form submit.

  • The uploaded files are read from the $_FILES PHP superglobal, in particular for the POST parameter named files.
  • The file tag is read from the \Request object for the POST parameter named file_tag.
  • If no file is selected, an error message is set as response of the controller action by calling the \Response::setFailedMessage() method.
  • On the other hand, if files are selected, their names and the entered file tag are returned in a message by calling the \Response::setSuccessMessage() method.

Controller uploadctrl.php

<?php
namespace app\controller;

class UploadCtrl extends \AppController {

    static protected function action_upload() {
        $response = new \Response();        
        if (!is_array($_FILES['files'])
                || !is_array($_FILES['files']['name'])
                || count($_FILES['files']['name']) === 0 
                || $_FILES['files']['name'][0] === '') {
            $response->setFailedMessage(NULL, 'Please, select a file.');
            return $response;
        }
        $request = new \Request();
        $fileCount = count($_FILES['files']['name']);
        $fileTag = $request->file_tag === NULL ? '<i>no tag</i>' : "<b>{$request->file_tag}</b>";
        $filenames = implode(', ', $_FILES['files']['name']);
        $response->setSuccessMessage('Upload', "Count of uploaded files: <b>$fileCount</b><br>"
            . "Uploaded files: <i>$filenames</i><br>"
            . "Choosen files tag : $fileTag<br>");
        return $response;
    }

}
PHP

Step 3 - Adding an "Upload files" item to the navigation menu

Finally, to give users access to the uploadview.php view, a menu item definition is added into the menu.php script of the Web App (see Get Started | New menu items for more information).

The menu.php script is located into the INSTALL_DIR/applications/default/app/ folder.

Script menu.php

static public function initAppMenuItems() {
    
    // ... Here, some menu items...
    
    \MenuManager::addMenuItem(NULL, 'uploadview', 'Upload files', 'fa-upload');
    
    // ... Here, other menu items...
    
}
PHP

Search

Sort order