Thursday, September 11, 2014

Upload file using AJAX in Yii

You can upload files using ajax. There are several different plugging that can be used to do that. Below one worked well for me.
http://www.phpletter.com/our-projects/ajaxfileupload/
Go to the above link and download the file. Put 'ajaxfileupload.js' file inside 'js' folder.
In order to use the file you should configure the path in 'main.php'.Go to 'protected/views/layouts/main.php' and add the below line.
<script src="<?php echo Yii::app()->request->baseUrl; ?>/js/ajaxfileupload.js" type="text/javascript"></script>

To upload the file you have to use the following code:
    <script language="Javascript">
        function ajaxFileUpload()
        {
            $.ajaxFileUpload
            (
                {
                    url:'index.php?r=workspace/usImport',  //the controller action path
                    secureuri:false,
                    fileElementId:'myfile',
                    dataType: 'json',
                    data:{stage:$('#trackIteration').val()}, //data you want to pass to the action
                    success: function (data, status)
                    {
                        if(typeof(data.error) != 'undefined')
                        {
                            if(data.error != '')
                            {
                                alert(data.error);

                            }else
                            {

                               alert('File uploaded successfully'); 

                             }

                            }
                        }
                    },
                    error: function (data, status, e)
                    {
                        alert(e);
                    }
                }
            )
            return false;
        }
    </script>
Create your form as below

                <form name="formMy"  id="formMy"  enctype="multipart/form-data" method="post">
                      Choose a file to import
                    <input type="file" style="margin-top: 8px;" id="myfile" name="myfile"><br>

                    <button class="btn btn-primary" id="usImport" name="usImport"                    onclick="return ajaxFileUpload();"> Import</button>    /*Calling  ajaxFileUpload() function*/
                    <button class="btn btn-primary">Cancel</button>
                </form>
In order to upload a file you need to set the form encrypt type to 'multipart/form-data'.

Inside php action you can do something like below

$fileElementName='myfile'  //file element name

   if(!empty($_FILES[$fileElementName]['error']))
        {
            switch($_FILES[$fileElementName]['error'])
            {

                case '1':
                    $error = 'The uploaded file exceeds the upload_max_filesize directive in php.ini';
                    break;
                case '2':
                    $error = 'The uploaded file exceeds the MAX_FILE_SIZE directive that was specified in  the HTML form';              
                    break;
                case '3':
                    $error = 'The uploaded file was only partially uploaded';
                    break;
                case '4':
                    $error = 'No file was uploaded.';
                    break;

                case '6':
                    $error = 'Missing a temporary folder';
                    break;
                case '7':
                    $error = 'Failed to write file to disk';
                    break;
                case '8':
                    $error = 'File upload stopped by extension';
                    break;
                case '999':
                default:
                    $error = 'No error code avaiable';
            }
        }elseif(empty($_FILES['us']['tmp_name']) || $_FILES['us']['tmp_name'] == 'none')
        {
            $error = 'No file was uploaded..';
        }else
       {
         /*The code goes here  */
        }




No comments:

Post a Comment