AJAX Multiple File Upload Form Using jQuery

Posted in AJAX jQuery

AJAX Multiple File Upload using jQuery

Multiple file upload forms are sometimes essential for your web application but managing upload from multiple file input boxes becomes a bit tedious and lengthy. But thanks to jQuery using which we can make this task easier too. Today I’m going to create an AJAXified multiple file upload form that uses a lot lesser server side code and also provides a very nice user interface.

For this tutorial, i’ll be using latest version of jQuery and Ajax upload library by Andrew Valums. Grab both libraries and add them to your page header

The HTML Structure

As i said, the upload form will be intuitive, we won’t be using the classic File input box. So, First of all create the upload button on which user will click to open the File Selection dialog.

<div id="upload" >Upload File</div>

You can use any element you want for the button. I just applied some basic style to this div, you can apply any style you wish to make it look more attractive.

#upload{
	margin:30px 200px; padding:15px;
	font-weight:bold; font-size:1.3em;
	font-family:Arial, Helvetica, sans-serif;
	text-align:center;
	background:#f2f2f2;
	color:#3366cc;
	border:1px solid #ccc;
	width:150px;
	cursor:pointer !important;
	-moz-border-radius:5px; -webkit-border-radius:5px;
}

I also added a span element next to upload button to show various messages during processing. And to show the uploaded files to the user, i added an unordered list next to the button. Here’s the complete html code.

<!-- Upload Button-->
<div id="upload" >Upload File</div><span id="status" ></span>
<!--List Files-->
<ul id="files" ></ul>

The PHP Code

To upload the files to server, here’s a basic file uploading script in PHP that displays ‘success’ if file uploaded successfully otherwise displays ‘error’.

upload-file.php

<?php
$uploaddir = './uploads/'; 
$file = $uploaddir . basename($_FILES['uploadfile']['name']); 
 
if (move_uploaded_file($_FILES['uploadfile']['tmp_name'], $file)) { 
  echo "success"; 
} else {
	echo "error";
}
?>

The JavaScript Code

And lastly the javascript part. The AJAX Upload library you included earlier will do all the heavy lifting for you. Here’s the JavaScript Code you’ll need.

$(function(){
	var btnUpload=$('#upload');
	var status=$('#status');
	new AjaxUpload(btnUpload, {
		action: 'upload-file.php',
		//Name of the file input box
		name: 'uploadfile',
		onSubmit: function(file, ext){
			if (! (ext && /^(jpg|png|jpeg|gif)$/.test(ext))){ 
                  // check for valid file extension 
				status.text('Only JPG, PNG or GIF files are allowed');
				return false;
			}
			status.text('Uploading...');
		},
		onComplete: function(file, response){
			//On completion clear the status
			status.text('');
			//Add uploaded file to list
			if(response==="success"){
				$('<li></li>').appendTo('#files').html('<img src="./uploads/'+file+'" alt="" /><br />'+file).addClass('success');
			} else{
				$('<li></li>').appendTo('#files').text(file).addClass('error');
			}
		}
	});
});

Code explanation: to use the AJAX Upload library we need to initialize the AjaxUpload object and provide it with parameters. The first parameter is the id of the button element on which the user will click and second is the server side script that’ll handle file upload. The second parameter can accept an array of various options to give you more control over the process.

And that’s exactly what i’ve done.

  • The action field is the path to server side script,
  • name is the name of file input box(hidden) which will be used for upload. If you change this value, make sure to change the server side script corresspondinly.
  • onSubmit lets you perform some function before the file is uploaded e.g. you can check the file extension like i’ve done above or show a status message.
  • onComplete lets you perform some action after the upload is complete e.g. I’ve shown the uploaded image to the user.

And if you want to limit the number of files that a user can upload at a time, simply use this.disable() within onSubmit or onComplete to disable the upload button after checking for some condition.

Note: The file upload using AJAX is not true ajax as it uses hidden iframe to upload the form data but his whole process is transparent by using the AJAX Upload library and gives a feel of AJAXified file upload.

View Working Demo or Download Source Code n Try.

Tags:

Share


Subscribe to Full RSS Feed

RSS FeedIf you found this article useful, then consider subscribing to our RSS Feed or e-mail updates to stay updated with latest Web Design/ Development articles. You can also follow @webdevplus on twitter for latest updates.

50 Responses (Add Your Comment)

  1. Phaoloo says:

    Step by step guidelines, really helpful for all developers.

  2. alan says:

    hi. this sounds great – but where is the multiple bit? I checked out the demo and it only allows one file at a time to be selected and uploaded..

  3. virua says:

    Good work. Thank you.

  4. abada says:

    nice work :D

    but what can i do if i want to cancel uploaded image

    can add checkboxe beside than images to check or unchecked

  5. elbstar says:

    Hi,
    I have tried a lot of solutions uploading images but this one here is the best I have seen.
    Very easy to implement.

    Thanks for this great work,
    elbstar

  6. Naresh says:

    hey great work. that seems very fruitful. thanks.

  7. cease says:

    during the demo , I only see one file at a time upload like alan… strangeness

  8. Atujpay says:

    Gracias!!! Fabuloso tutorial, claro que en mi caso lo hice con ASP y no con PHP.

  9. nice tut….
    but can you help me, how to implement with database.

    example:
    fileupload1 will save in column foto1 in mysql,
    fileupload2 will save in column foto2 in mysql

  10. mark says:

    great work!
    nice!

  11. Zameer says:

    Really a great job………….

    Jai Ho,

    Cheers!
    Zameer

  12. PF says:

    Good work but it doesnt work in firefox..

  13. Zameer says:

    Hi,
    If I am running on http://www.mydomain.com and upload script is running on images.mydomain.com
    will it work?

    I’m getting error
    Permission denied to get property HTMLDocument.readyState on line 455

  14. Neel says:

    Excellent Article for file uploading I learn it easily

  15. Skeptik says:

    Judging from the demo, this doesn’t work at all. You still have to click “upload” once for each file. Why is it that there is almost no information on the internet on how to create a multiple upload script? Gmail does this perfectly: you click one button and a file chooser pops up where you can shift-select multiple files. Why can’t I do that? What if my users want to upload 1000 pictures at once? or simply an entire directory? Why is this such a hard thing to do?!!!

    • linler says:

      1000 pics eyh? yeah right

    • Ryan says:

      Gmail can only accomplish this by using Flash.. if you inspect the file upload element you will see:

      Disable Flash in your browser and the multi-file upload doesn’t work.

  16. Lucas says:

    Demo, does not seem to work on Firefox 3.5 nor on IE8. It forces me to select only one file?

    Can that be fixed?

    Thanks,
    Lucas

  17. sonal says:

    hi,
    i want to upload mp3 files using this.but it shows error.
    Please someone give me fast reply.

  18. Swetha says:

    Hi,
    I am no Javascript expert, but I still tried to add some code to remove the uploaded files, so that users can remove an image if they uploaded it by mistake. But it does not work. Can you please add the code to do the same?

    Thanks.

  19. Jake says:

    This is a great script/function, however; it would be the bomb if it had a delete function!!

    • Swetha says:

      I agree with you Jake. I have tried to implement that function, but guess I have to learn more about AJAX before I succeed. Maybe the developer of the script would be kind enough of to add that function for us. I would really be helpful for newbies like us. Thanks.

  20. Tahir says:

    Hi,

    Not a php person but i really would like to use this one on my classic ASP site (JScript as server side). Could you please translate php to JScript for me?

    Also, php page is only returning success where as oncomplete function has 2 parameters onComplete: function(file, response), where is this file coming from?

    A side note, when the button is clicked, file picker shows up and as soon as the file is selected upload starts. Can we put the selected path to the file inside a textbox and then when submit button is clicked the upload should happen?

    Thanks

    • Swetha says:

      I think that would really help if the developer could do that. That way, we can show list of multiple files and then upload them in one go. Another idea to improve would be to show the image upload status or the transfer status. Hope the developer will get some time to implement that.

  21. Silviu says:

    Is it possible to increase filesize ? I have changed $size in upload-file.php and file_size_limit in index.html, flash works fine, but upload does not work. Is I try to view the uploaded file, I receive a 404 error.

    • Swetha says:

      Looks like you are encountering a page not found error. Try to see what you are posting the form to. Basically that means you do not have some file that the script is expecting. Hope that helps.

  22. lalji halai says:

    Great how we can add delete button?
    http://www.seoname.com

  23. Ruben says:

    I got it all working perfectly! I made it so that the php adds a random key to the file name. Like: n32nd_filename.jpg

    But how do i get this “key” printed when the files are successfully uploaded?

  24. Flexxall says:

    I have the upload working great and it was easy to set up. Is there a way to add a check to see if the file exists and if so return a filename already exists error. If you can assist with this it would be perfect :)

  25. zep says:

    NOT work with IE8, NOT work with Firefox3.5, NOT work with Crome.
    This is not multiple upload, this is a single upload.
    Fix it.

  26. ramesh says:

    hello,
    this application works good……..
    i search for this code in many sites atlast i found here

Comments are closed for this post.