Creating Ajax based file uploaders

Creating Ajax based file uploaders

15 162570

I got one interesting theme. How to upload files without refreshing whole page during submitting. Hope this will interesting to you. Lets check 2 methods – using ordinary iframes and external library. Also I will using jQuery in work too (I like it).

Here are samples and downloadable package:

Live Demo

[sociallocker]

download in package

[/sociallocker]


Ok, download the example files and lets start coding !


Step 1. HTML

As usual, we start with the HTML.

This is our main page code with both samples.

templates/main.html

<script src="js/jquery.min.js"></script>
<script src="js/ajaxupload.3.6.js"></script>
<script src="js/jquery.ui.widget.js"></script>
<script src="js/jquery.ui.accordion.js"></script>
<script src="js/main.js"></script>
<link rel="stylesheet" href="templates/css/jquery.ui.theme.css" type="text/css" />
<link rel="stylesheet" href="templates/css/jquery.ui.accordion.css" type="text/css" />
<link rel="stylesheet" href="templates/css/main.css" type="text/css" />
<div class="examples">
    <div id="accordion" class="accordion">
        <h3><a href="#">Ajax file upload into (hidden) iframe</a></h3>
        <div class="sample_1">
            <form id="file_upload_form" method="post" enctype="multipart/form-data" action="index.php" target="upload_target">
                <input name="file" id="file" size="50" type="file" />
                <input type="submit" name="action" value="Upload" /><br />
                <input type="text" name="variable" value="extra values" />
                <input type="hidden" name="sample" value="1" />
            </form>
            <button onclick="$('#upload_target').slideToggle(500)" >show iframe</button>
            <iframe id="upload_target" name="upload_target" src=""></iframe>
            <div style="clear:both;"></div>
            <div id="response1">awaiting for upload</div>
            <div style="clear:both;"></div>
            <p>
                First example of ajax upload. Most easy one. Just choose any image and clock 'Upload' button to process. Also you can send visible or hidden extra information. In iframe I will draw result of work. Plus we have response behavior of upload result.
            </p>
        </div>
        <h3><a href="#">Ajax file upload using ajaxupload.3.6.js library</a></h3>
        <div class="sample_2">
            <div id="ajxiupload2">Upload button</div>
            <div id="response2">awaiting for upload</div>
            <div style="clear:both;"></div>
            <p>
                Another good sample. Now we will using special library - ajaxupload.3.6.js. This library from <a rel="nofollow" href="http://valums.com/ajax-upload/">here</a>. Both samples very interactive and useful. Try it!
            </p>
        </div>
    </div>
</div>

Step 2. CSS

Here are used CSS styles.

templates/css/main.css

body{background:#eee;font-family:Verdana, Helvetica, Arial, sans-serif;margin:0;padding:0}
.examples{background:#FFF;width:570px;font-size:80%;border:1px #000 solid;margin:3.5em auto 2em;padding:1em 2em 2em}
.accordion h3{margin:0}
.accordion form{border:1px solid;background:#E6E6E6;border-color:#C3C3C3 #8B8B8B #8B8B8B #C3C3C3;margin:.5em 0;padding:.5em}
.accordion form label{margin-right:1em;font-weight:700;color:#900;font-size:10px}
iframe#upload_target{width:500px;height:400px;border:1px solid #ddd;float:left;display:none}
#response1,#response2{font-size:18px;text-align:center;padding:10px;width:200px;border:1px solid #ddd;margin:10px 0}
#ajxiupload2{background-color:#afe;font-size:18px;text-align:center;padding:10px;width:200px;border:1px solid #ddd;margin:10px 0}

templates/css/jquery.ui.accordion.css and templates/css/jquery.ui.theme.css

This is common files – styles of jquery elements. No need to give full code of that file here. It always available as a download package

Step 3. JS

Here are necessary JS file to our project.

js/main.js

$(document).ready(function(){
    $("#accordion").accordion({autoHeight: false,navigation: true});
    // for sample 1
    var $oResponse1 = $("#response1");
    $("#upload_target").load(
        function() {
        var ret = frames['upload_target'].document.getElementsByTagName("div")[0].innerHTML;
        var data = eval("("+ret+")"); //parse json
            $oResponse1.text(data.html);
        }
    );
    // for sample 2
    var $oResponse2 = $("#response2");
    var button = $('#ajxiupload2'), interval;
    new AjaxUpload(button,{
        action: 'index.php',
        data : {
            'extra_info' : 'some extra info',
            'sample' : 2,
        },
        name: 'image',
        onSubmit : function(file, ext){
            this.disable();
        },
        onComplete: function(file, response){
            this.enable();
            var data = eval("("+response+")"); //parse json
            $oResponse2.text(data.html);
        }
    });
});

js/ajaxupload.3.6.js, js/jquery.min.js, js/jquery.ui.accordion.js and js/jquery.ui.widget.js

This is common files – jQuery library with addon and our new library. No need to give full code of that file here. It always available as a download package

Step 4. PHP

Ok, here are all used PHP file:

index.php

<?php
// set error reporting level
if (version_compare(phpversion(), "5.3.0", ">=") == 1)
  error_reporting(E_ALL & ~E_NOTICE & ~E_DEPRECATED);
else
  error_reporting(E_ALL & ~E_NOTICE);
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    if ((int)$_POST['sample'] == 1) {
        echo '<div>' . json_encode(array(
            'html' => 'uploaded',
            'code' => 1,
        )) . '</div>';
        echo '<pre>';
        echo "\$_POST variables:\n";
        print_r($_POST);
        echo "\$_FILES variables:\n";
        print_r($_FILES);
        echo '</pre>';
        exit;
    }
    if ((int)$_POST['sample'] == 2) {
        echo json_encode(array(
            'html' => 'uploaded',
            'code' => 1,
        ));
        exit;
    }
}
require_once('templates/main.html');
?>

Live Demo

Conclusion

Today I told you about ajaxy upload methods. Sure that you will happy play with it. You can use this material to create own scripts into your startups. Good luck!

SIMILAR ARTICLES

Understanding Closures

0 24640

15 COMMENTS

  1. Nice tutorial, having searched the internet a few hours I now think I have found something close to what I need. I’m having some trouble with getting a file to upload although the form says ‘uploaded’ the file does not appear on the server.

    Is line 9 of the main.js file the only place I need to set the upload target?

    I have tried changing this with no success.

    Any help would be greatly appreciated.
    Cheers, John :)

  2. Your site is amazing.I am very impressed to see this,i want to come back for visiting your site.Keep doing Good as well as you can..

  3. Hi,
    I am not using PHP. Only HTML. Where will the file be uploaded? Where is the upload path defined?
    Sorry for sounding so dumb…I am trying this for the first time using JQuery.

    thanks
    S

  4. 2 sindhu
    In my demo I don`t downloading received files itself, but you always can accept it in incoming $_FILES
    and you can define your own upload directory. But this functional will in PHP

  5. Yes, very nice but leave the BIG question everyone like to know HOW TO ……do

    “In my demo I don`t downloading received files itself, but you always can accept it in incoming $_FILES
    and you can define your own upload directory. But this functional will in PHP”

    ???????????????????????????????

    • 2 Sony: This is very easy to handle with files (I prepared very easy sample):

      $uploaddir = ‘/var/www/data/’;

      echo ‘<pre>’;
      if (move_uploaded_file($_FILES[‘userfile’][‘tmp_name’], $uploaddir . $_FILES[‘userfile’][‘name’])) {
      print ‘File is valid, and was successfully uploaded. Extra info:<br />’;
      print_r($_FILES);
      } else {
      print ‘Possible file upload attack! Extra info:<br />’;
      print_r($_FILES);
      }
      echo ‘</pre>’;

  6. If someone will interested in – how to safely accept the file – I can prepare new post about this too :-)

  7. This plugin is really cool. It is starting the upload as soon as i select the file and click “open” in the file open dialog. But i want to start the upload when i click a “save” button in my form. How to do this? Please help me

    • Hi Srivathsa,
      It seems that you have to change params of AjaxUpload object (in main.js file). Possible you will able to pause sending data here.

    • Hi Bikash,
      In this old demo we used direct access to IFRAME content, this access is disabled by default in Chrome. We shouldn’t work with iframes nowadays.

  8. i want to upload videos and this demo only upload the image files how can i change it to upload video files please help

    • Hello,
      First at all, I’d like to remind you that this is pretty old demo, I can recommend that you update jQuery version in this script as minimum.
      As I see, this script doesn’t work only with images, it can work with any files

  9. how can i allow choosing multiple files in the top most(first demo) method from the file dialog.instead of user having to click the upload div area again and again

    • Hi Shad,
      This depends on the browser. Never version of firefox and chrome support this because they started to implement HTML5 specification. This is the syntax:

      <input type="file" multiple=""/>

      Firefox >= 3.6, Chrome >= 2, Safari >= 4 support multiple file input.
      For older browsers the only good solutions are flash or javascript plugins

Leave a Reply