AJAX Multiple File Upload Form Using jQuery

Jun 24th, 2009 – 50 Comments »
Share: (272) Delicious FacebookPosted 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.

view plaincopy to clipboardprint?
<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.

view plaincopy to clipboardprint?
#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.

view plaincopy to clipboardprint?
<!– 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

view plaincopy to clipboardprint?
<?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.

view plaincopy to clipboardprint?
$(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: jquery forms jquery plugins user interface

Bookmark n Share
Bookmark to Delicious
272 bookmarks so far
Stumble this article
digg

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.

Related Posts
Multiple File Upload With Progress Bar Using jQueryMultiple File Upload With Progress Bar Using jQuery
Create a Dynamic Scrolling Content Box Using AJAX
New WordPress Plugin: WDP AJAX Comments
AJAX User Poll Using jQuery and PHPAJAX User Poll Using jQuery and PHP
50 Responses (Add Your Comment)
Phaoloo says:
June 25, 2009 at 8:31 PM
Step by step guidelines, really helpful for all developers.

alan says:
June 25, 2009 at 9:12 PM
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..

virua says:
June 26, 2009 at 12:38 PM
Good work. Thank you.

abada says:
June 26, 2009 at 7:07 PM
nice work 😀

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

can add checkboxe beside than images to check or unchecked

elbstar says:
June 27, 2009 at 7:56 PM
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

Naresh says:
June 28, 2009 at 1:31 PM
hey great work. that seems very fruitful. thanks.

cease says:
June 28, 2009 at 3:07 PM
during the demo , I only see one file at a time upload like alan… strangeness

Atujpay says:
July 5, 2009 at 11:33 PM
Gracias!!! Fabuloso tutorial, claro que en mi caso lo hice con ASP y no con PHP.

Agus Puryanto says:
July 7, 2009 at 2:23 PM
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

mark says:
July 8, 2009 at 11:00 PM
great work!
nice!

Zameer says:
July 10, 2009 at 10:09 AM
Really a great job………….

Jai Ho,

Cheers!
Zameer

PF says:
July 17, 2009 at 12:13 AM
Good work but it doesnt work in firefox..

webdeveloperplus says:
July 17, 2009 at 5:09 AM
it works in FF, just the cursor doesn’t change when you mouse over the upload button, or you might have javascript disabled in firefox

Zameer says:
July 22, 2009 at 1:15 PM
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

webdeveloperplus says:
July 23, 2009 at 9:41 AM
it’ll work if you place javascript files on images.mydomain.com

Zameer says:
July 23, 2009 at 9:53 AM
ajaxupload javascript is already running on images.mydomain.com. But still I’m in trouble.

webdeveloperplus says:
July 23, 2009 at 9:59 AM
did u place jQuery file on that sub-domain?

Neel says:
July 25, 2009 at 10:24 PM
Excellent Article for file uploading I learn it easily

Skeptik says:
August 2, 2009 at 10:39 AM
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:
August 8, 2009 at 4:50 PM
1000 pics eyh? yeah right

Ryan says:
October 14, 2009 at 5:02 AM
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.

Lucas says:
August 6, 2009 at 9:19 PM
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

sonal says:
August 11, 2009 at 8:51 AM
hi,
i want to upload mp3 files using this.but it shows error.
Please someone give me fast reply.

Swetha says:
August 20, 2009 at 12:48 AM
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.

Jake says:
August 29, 2009 at 3:08 AM
This is a great script/function, however; it would be the bomb if it had a delete function!!

Swetha says:
September 7, 2009 at 3:33 AM
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.

Tahir says:
September 15, 2009 at 8:49 AM
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:
October 2, 2009 at 8:33 AM
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.

Silviu says:
September 17, 2009 at 4:11 PM
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:
October 2, 2009 at 8:34 AM
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.

lalji halai says:
October 13, 2009 at 1:24 AM
Great how we can add delete button?
http://www.seoname.com

Ruben says:
October 15, 2009 at 4:03 AM
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?

Flexxall says:
October 15, 2009 at 10:04 PM
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 🙂

zep says:
October 20, 2009 at 1:27 PM
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.

ramesh says:
October 23, 2009 at 11:00 AM
hello,
this application works good……..
i search for this code in many sites atlast i found here

Comments are closed for this post.

« Previous Post
Create Featured Content Slider Using jQuery UINext Post »
15 jQuery Tutorials For More Interactive Navigation
Subscribe:Subscribe to RSS Feed
Subscribe to RSS
Subscribe to email updates
Follow on Twitter
Sponsors
Recent Articles
40 Fresh & Beautiful Examples of Websites With Large Backgrounds
Quick & Easy Way to Implement Drag n Share With jQuery
Tips to Write Better CSS Code
12 Lesser Known But Useful WordPress Hacks
25 Amazing & Free Flash Based Image Galleries
15 Ways to Improve CSS Techniques Using jQuery
AJAX User Poll Using jQuery and PHP
25 New & Useful PHP Techniques & Tutorials
13+ Fresh and High Quality Texture Sets & Collections
15 Time Saving CSS Tools You Should Be Aware Of
Popular Articles
12 Lesser Known But Useful WordPress Hacks12 Lesser Known But Useful WordPress Hacks

Oct 30, 2009 – 21 Comments »

15 Ways to Improve CSS Techniques Using jQuery15 Ways to Improve CSS Techniques Using jQuery

Oct 20, 2009 – 25 Comments »

25 New & Useful PHP Techniques & Tutorials25 New & Useful PHP Techniques & Tutorials

Oct 13, 2009 – 30 Comments »

21 Brilliant jQuery Image Gallery/Slideshow Plugins21 Brilliant jQuery Image Gallery/Slideshow Plugins

Sep 14, 2009 – 17 Comments »

25 Incredibly Useful CSS Tricks You Should Know25 Incredibly Useful CSS Tricks You Should Know

Sep 01, 2009 – 71 Comments »

30+ Fresh & Amazing jQuery Plugins & Tutorials30+ Fresh & Amazing jQuery Plugins & Tutorials

Aug 19, 2009 – 7 Comments »

Cool Stuff (from around the web)
50 Fresh and Free WordPress 3 Series Compatible Themes

10 Important jQuery Selectbox/DropDown Plugins

15 Powerful jQuery Tips and Tricks for Developers

20 New Examples of Minimal Websites

Building Tabbed Navigation using SpryTabbedPanels

How to Create a Basic WordPress Theme with Gantry Framework

15 Fresh jQuery Menu Plugins and Tutorials