Upload multiple files with a single file element
Published July 13th, 2005STOP PRESS: There is now a new version here, based on Mootools.
Please note: As you will notice if you take the time to read this article, you will see no mention of the word ‘Ajax’ (apart from the ones in this paragraph). That’s because this technique has nothing whatsoever to do with Ajax — and I never claimed that it did. The fact that people are linking to this page and suggesting some sort of Ajax-y connection has nothing to do with me. So please, no more “but it’s not Ajax!” comments.
Thank you.
10th October 2005: Updated to add Safari support. Many thanks to Luis Torrefranca, Jamie Butler and Matt Kurpiewski (http://www.law.pitt.edu) and Shawn Parker & John Pennypacker (http://www.fuzzycoconut.com) for their help. Please download again.
2nd October 2005: I updated the script to fix a potentially nasty bug.
If you have a form where you want to allow a user to upload more than one file, you’re stuck with either adding as many file input elements as the number of files you want to upload, or possibly having new ones appear ‘magically’ through Javascript.
I was mulling over some ideas while walking home from work last week, when I came up with what I thought might be a quite cunning (and more atttractive and useable) way to allow a form to use a single file input element — sort of — to upload multiple files. Since you can only store file upload information in a file upload element (<input type=”file”>), you’ll always need to have one element per file to be uploaded. But what occurred to me is that you don’t need to display all those file elements.
Using the DOM, it’s actually a relatively simple matter to conceal a file element once a file has been chosen, and add a new (empty) one in its place. And to keep doing so, as many times as you like. It all happens so quickly, that it appears that there’s only one input element.
To make it even smarter, you can then read the value of each element (ie. the name of the file to be uploaded) and build a list, in whatever format you like, of chosen files. And with a little bit more code you can add the ability selectively to remove files that have been picked.
Enough waffling — here’s a demonstration:
I’ve deliberately left all styling out of the class, so the list is ugly (you can edit this yourself quite easily). And obviously there’s no submit button (I don’t want a load of junk files uploaded to my host, thanks) so I can’t show it ‘in action’ as such. You’ll just have to take my word for it, that it really does work. Or of course, download the (zipped) file and try it for yourself (don’t use the version included in this page, it’s slightly different).
The code is heavily commented to explain a) how to use it and b) how it works, although I’ve also included a compressed, comment- and whitespace-free version which is significantly smaller. I’ve tested it successfully with Mozilla Firefox 1.04, MSIE 6 and Opera 8 but I’m fairly confident that it’ll work with most, if not all, modern DOM-enabled browsers — if you can confirm or disprove this, please let me know.
One thing to be aware of when allowing mutliple uploads is that there are generally limits on the quantity of data that can be sent in any one request — for example, PHP has a default limit of 2MB (although this can be changed, using ini_set(‘upload_max_filesize’, ‘[new size]M’) where new size is the maximum number in megabytes — this will not work if safe mode is enabled on your host).
If you’re looking for help handling the files once they’ve been uploaded, you could do worse than take a look at this this comment by Shawn Parker (thanks again, Shawn!).
The licence for this code is simple: use it how you like, but don’t blame me if it breaks anything. Also, it’d be nice if you’d leave the credit (with the link to this site) in the code.
nate on August 19, 2005
Thanks for your code! I think there might be a bug in multifile.js, though. When I first tried it, I was having problems that the file input was immediately disabled after I intialized MultiSelector. Problem seemed to be with:
if( this.count >= this.max || !this.max ){
element.disabled = true;
};
If max is ‘0′ (no limit), (! this.max) is true, and the element is disabled before it is used. I think you want “if (this.max > 0 && this.count >= this.max)” or the like.
Stickman on August 25, 2005
Thanks for the bug report — you’re absoultely right. I’ve changed the code such that if max isn’t specified, it’s set to -1. The code then checks for this value when verifying the maximum number of files.
Thuven on September 12, 2005
Hi dude. thanks a lot for the helping hand .. you rock!! …
Le on September 14, 2005
Hi dude, thanks a lot for the script…
.
Dougal Campbell on September 27, 2005
If you have javascript disabled, you get one file input, but it still says “maximum 3″. You might want to either generate the “maximum” message via JS, or perhaps fall back to displaying all of the file inputs when there’s no scripting. You could default to displaying them all, and hide the extras with JS when it’s available.
Mark Wubben on September 29, 2005
There’s a memory leak in the code though. (Circular reference through closures leads to memory leaks in IE.) To fix it, set the `list_target` and `element` variables to null once you’ve set all the events.
More here: http://novemberborn.net/javascript/event-cache
sean on September 29, 2005
Nice! On several of the sites I run, I just have 10 file upload boxes so you can choose to upload up to 10 files at a time (pics mainly), and I always thought it looked like hell. This will make it a lot better
legionnewbie on September 29, 2005
Dont suppose anyone would want to help out a newbie. How do I
3. Instantiate a MultiSelector object, passing in the DIV and an (optional) maximum number of files
* eg. var multi_selector = new MultiSelector( document.getElementById( ‘files_list’ ), 3 );
Where do I put this ? in the _js file or the html file.
sorry for the newbiness
neal on September 29, 2005
Just a thought, but how does it handle the case when three files have been selected and the first one is then deleted and another one added?
I only ask as looking at the code it appears you will get two input elements with the same name.
Kae Verens on September 30, 2005
The demo does not work in Konqueror. I have not checked the source, though, to see what was wrong, but I’m sure it is easy to fix. If I fix it before you do, then I’ll alert you with the code changes.
Touxe on September 30, 2005
Thanks a lot for this very useful multi upload form.
I’d like to change the “list-file” output for a table.
In the first cell, the filename and in the second the button. I would like to do this in order to have all filename and button align.
I’have tried but i’m a newbie. I’m able to create new line in my table but i can’t delete it.
Can someone help me … thanks a lot.
ps : sorry if you don’t understand me
ceejayoz on October 1, 2005
That is a beautiful approach! Wow!
Dustin Diaz on October 1, 2005
What a brilliant idea!
Simple, Elegant, well documented and fast. The source is easy to follow and had no problems iterating through the logic. well done.
Next time I run into a case where I need to upload multiple files, I’ll remember to keep this in mind.
Jose on October 1, 2005
Hi, i don’t know what am i doing wrong, all i get is a “Error: element has no properties” Javascript error and a think i followed all the instructions given.
Does anyone have the same error?
Stickman on October 2, 2005
To everyone who’s linking to me, and for all the praise: thanks, I’m flattered.
To everyone having problems getting this to work: I’ve added an example HTML file to the .zip.
To neal: you’re right about the duplicate name problem, thanks for pointing it out. I’ve added a not-very-clever fix for the moment, until I get time to rewrite it properly.
To Mark Wubben: I’m aware of IE’s memory leak problems but hadn’t really thought about them when writing this. When I get a moment I’ll look at rewriting to take this into account.
To Kae Verens: I don’t have access to a machine running KDE to test on Konqueror. Any suggestions as to what the problem is (and potential solutions) are most welcome.
I’m about to go on holiday for a week, so no more updates will occur until I get back.
Jose on October 2, 2005
Now is working great! Thanks man, awesome work!
tdgraphix on October 2, 2005
Great Idea and Implementation! Works like a charm!
mattl on October 2, 2005
Works in Safari too.
Tom on October 2, 2005
Nice but it has problems
On Mac OSX 10.4.2 it works fine with Firefox but does not perform any uploads (error: 4) when used in Safari (2.0.1) In my test file the first form using your sample fails but the second vanilla upload works fine. Any help would be appreciated.
Tom
“;
print_r ($_POST);echo “”;
?>
” method = “post”>
Files:
var multi_selector = new MultiSelector( document.getElementById( ‘files_list’ ), 3 );
multi_selector.addElement( document.getElementById( ‘my_file_element’ ) );
Tom on October 2, 2005
neal,
why not just name the input something like “”userfile[]” and then deal with the php array in $_FILES on accepting the POST?
Hans on October 3, 2005
Nice work!
It is annoying to have a script tag in the middle of the code. How about putting the entire script in one file? Then you need to add some more code. Note that the code that was previously in the script tag, is now in the _init code:
addEvent(window, “load”, multiselector_init);
function multiselector_init() {
var multi_selector = new MultiSelector( document.getElementById( ‘files_list’ ), 3 );
multi_selector.addElement( document.getElementById( ‘my_file_element’ ) );
}
function addEvent(elm, evType, fn, useCapture)
// addEvent and removeEvent
// cross-browser event handling for IE5+, NS6 and Mozilla
// By Scott Andrew
{
if (elm.addEventListener){
elm.addEventListener(evType, fn, useCapture);
return true;
} else if (elm.attachEvent){
var r = elm.attachEvent(“on”+evType, fn);
return r;
} else {
alert(“Handler could not be removed”);
}
}
David Kaneda on October 3, 2005
I can confirm the script doesn’t work in the most recent Safari-
Adam on October 3, 2005
Thanks man! I was thinking about the same thing the other day after work, with a quick Google, I found you. It’s good to know we don’t all have to do the work twice as long as there are plenty of people like us out there.
Noel Jackson on October 4, 2005
This is awesome. Mind if I use it in PhotoStack???
Noel Jackson on October 4, 2005
Well, I thought I would, but it doesn’t work in safari! DOH!
Jim Johnson on October 4, 2005
Just saying thatnk found the element I already had plus used your element.onchange=funtion rather than my addHandler()
works cross browser better Appreciate the code
delvinj on October 5, 2005
Nice work. anyone tried this with a servlet or jsp on the recieving end?
~d
Noel Jackson on October 5, 2005
Anyone know how to get this working in Safari? I’d love it if you could tell me.
Shawn on October 5, 2005
I believe that it has something to do with assigning it a display of ‘none’ when created.
CSS behavior will have an element like an image not even load from the server with a display: none; – and if you remove line 77 ( this.style.display = ‘none’; ) from the js file Safari works.
There needs to be another way of hiding the newly created file input element. Maybe hiding a div that contains it instead of the element itself…
Noel Jackson on October 5, 2005
how about text-indent: -1000 em; ???
Shawn on October 5, 2005
Tried that and it didn’t like it. On top of that – whenever I did get something to work in Safari, Firefox would freak out and either show a sliver of the element or not work like Safari did…
Granted, I’m not a CSS or Javascript Guru by any means – I’m still learning – but there just might have to be some browser sniffing going on here.
A little browser sniffing could get this to work because every other browser responds to display: none being applied to the element while Safari liked having height: 0; width: 0; overflow: hidden; applied to it.
I know its archaic to browser sniff, but for now its the only way I found to do it. I might also try putting a size limit on the list div and make sure it does not grow, and make sure the new file input elements don’t run inline but that they each run on a new line – that way overflow: hidden could be applied to their parent element without styling the inputs themselves.
I didn’t have time to test that concept yet.
Luis Torrefranca on October 6, 2005
For a mailer, I added a browser sniffer and changed the style handling to this:
if (is_safari) {
this.style.position = ‘absolute’;
this.style.left = “-10000px”;
} else {
this.style.display = ‘none’;
}
I was also having some trouble retrieving the data, so we modified the element.name to use an array:
element.name = ‘attachment[]‘;
and retrieved it on the php processing page with:
$files = sizeof($_FILES['attachment']['name']);
for ($i = 0; $i
Luis Torrefranca on October 6, 2005
oops… code cut me off…
anyway, loop through from 0 through the array size. Then call them by:
$_FILES['attachment']['tmp_name'][$i] and so on
again, hope this helps
superkain on October 6, 2005
Looking Good man! Great inception.
Shawn on October 7, 2005
Luis – I just came back to post that same Safari fix – damn you! ; )
I got around the files thing by just doing a foreach on the $FILES array and only working on the entries that had an error of 0. Saved the extra hassle of having to do it client side.
Lets see if all my code makes it
$no_files = 0;
foreach($_FILES as $file)
{
switch($file['error'])
{
case 0:
// file found
if($file['name'] != NULL && okFileType($file['type']) != false)
$v = processFile($file);
// build string for confirmation display
if(isset($v) && $v == true)
{
showSuccess($file);
$no_files++;
}
break;
case (1|2):
// upload too large
$error[] = ‘file upload is too large’;
break;
case 4:
// no file uploaded
break;
case (6|7):
// no temp folder or failed write – server config errors
$error[] = ‘internal error – flog the webmaster’;
break;
}
}
Pranveer on October 7, 2005
where is catch.php
Shawn on October 7, 2005
Another Safari fix: I changed my delete button into an image button, and for some reason after I did that Safari wanted to refresh the page after doing that which also cleared my upload fields.
This can be avoided by simply adding:
return false;
to the end of
new_row_button.onclick= function(){
// Remove element from form
this.parentNode.element.parentNode.removeChild( this.parentNode.element );
// Remove this row from the list
this.parentNode.parentNode.removeChild( this.parentNode );
// Decrement counter
this.parentNode.element.multi_selector.count–;
// Re-enable input element (if it’s disabled)
this.parentNode.element.multi_selector.current_element.disabled = false;
return false; // add this to appease Safari
};
Leo on October 11, 2005
What does this have to do with AJAX??? Does “AJAX” manicker now get used for any clever Javascript hack? Don’t get me wrong, I think the script is a cool idea, but it’s not AJAX unless it sends micro-requests to server in an XML format and does micro-updates of those responses.
The whole point of AJAX is that I can send a request to server and update a part of the page without having to reload and re-render the whole page.
Stickman on October 11, 2005
You’re right, but then I never said it had anything to do with Ajax.
smith288 on October 11, 2005
AJAX is used very liberally these days. Its alot easier to say that than “asyncronis javascript connection without using xml…”
Stickman on October 11, 2005
True. But as has been pointed out, this widget is just DOM manipulation — there’s no client-server communication, unless you count the form submission (which is handled in the usual fashion).
Sheetal Jain on October 12, 2005
I have managed to get this working even by hiding the file control -Just the way Gmail does for email attachment -
Had to dig through gmails’s dirty secert
here is the solution
http://
Sheetal Jain on October 13, 2005
Ops! – I didn’t put the url in last posting
http://sheetaljain.blogspot.com/
Thanks
newbegin on October 13, 2005
hello
it good ….
now i am plan to use this …
Thanks
Marcos Lopez on October 14, 2005
It’s a wonderful solution, but…. what about having the ability to choose several files at the same time? or even all the files under a directory?
It would be very usefule a “select folder” winamp-style control
Thanx
Stickman on October 14, 2005
Not possible, I’m afraid. For very good security reasons, file input elements are very limited in their capabilities and there’s simply no way (that I’m aware of) to work around that.
I suppose it’s possible that you could achieve it in Internet Explorer using a custom ActiveX control, but I’m no expert on that sort of thing and anyway, that would of course kill cross-browser comptability.
MisterJ on October 18, 2005
Excellent script !
I have made a little mod in order to display only the filename i/o full path+filename :
element_work = element.value;
element_tab = element_work.split(“\\”);
nbr_elements = element_tab.length;
new_row.innerHTML = element_tab[nbr_elements-1];
instead of :
new_row.innerHTML = element.value;
cheers
Jpep on October 19, 2005
Can a javascript wiz please help me (if possible) change the delete button to the word ‘remove’. I’d rather use text instead of the button for style purposes. Thanks for the great work!
Jpep on October 19, 2005
Me again… Sorry, but I’m having a bit of trouble handling the multiple files using php. My original form was based on this example from php.net (http://us3.php.net/manual/en/features.file-upload.multiple.php). Here is my form…
I then use the following php just to test the first upload on the first file.
/ $userfile is where the file went on the webserver
$userfile = $_FILES['userfile']['tmp_name'][0];
// $userfile_name is the original file name
$userfile_name = $_FILES['userfile']['name'][0];
// $userfile_size is the size in bytes
$userfile_size = $_FILES['userfile']['size'][0];
// $userfile_type is the mime type
$userfile_type = $_FILES['userfile']['type'][0];
// $user_file error is any error encountered
$userfile_error = $_FILES['userfile']['error'][0];
I echo these variables and the result is that I don’t get any data for the above variables. When I change the input id to id=”my_file_elementXXXXX”. The upload works. So obviously I’m doing something wrong on the php end.
Any ideas? Thank you so much. Sorry for the multiple posts.
Jpep on October 19, 2005
Okay. I figured out what I was doing wrong. Obviously I cannot follow directions. If anyone else out there is having problems, make sure that your input field does not have a ‘name’ set. As per the instructions, make it look like this…
Then one way (not the best way) of process the files with php would be the following…
$file_count = sizeof($_FILES);
echo ‘Number of files: ‘ . $file_count .’…’;
for ($i=0; $i’;
echo ‘Size: ‘ . $userfile_size.”;
echo ‘Type: ‘ . $userfile_type .”;
echo ‘Error: ‘ . $userfile_error .”;
echo ”;
}
Jpep on October 19, 2005
Oops. My code got cut off. What’s the best way to post php? Anyway, on the server (php), I use…
$file_count = sizeof($_FILES);
to get the number of files uploaded
and then I just loop thru and process as needed using the file naming scheme provided by this script…
$thisfilename = ‘file_’ . $i;
$userfile = $_FILES[$thisfilename]['tmp_name'];
Hope that helps someone out.
Sudhir on October 19, 2005
Hi
I would like to use this script but I want to use the checkbox instead of delete button and I want to delete the checked files at once rather than deleting individually.
Please help me in getting this if anyone has work around.
Thanks in advance
Sudhir
Jpep on October 20, 2005
***Does not work in Netscape 7.02 / WinXP***
Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.0.2) Gecko/20030208 Netscape/7.02 (VAUSSU03)
Yes, me again. I noticed that this demo doesn’t work in the above environment. In my test, I must hit the browse button again after selecting the file for the file to show in the file list below the form.
In further tests, the files do not appear to upload either.
Can anyone else confirm this behavior?
Stickman on October 20, 2005
I don’t have NS7 installed but I’ve tried it in NS8beta and it appears to work.
If I could think of an elegant, reliable way (ie. not sniffing for specific browsers/versions) to exclude those browsers that are known to have problems, then I’d implement it. Suggestions welcome.
hm on October 22, 2005
doesnt do crap, just dumps me at http://localhost/your_script_here.script
Stickman on October 22, 2005
Flyboy on October 24, 2005
After uploading the files (done through ajax, so the uploadform never leaves the page) I want to reset the form so it’s ready to select a bunch of other files and then upload them too.
But the submit button doesn’t react any more then.
Is this a build in protection against people double clicking the button if they think nothing happend?
And if so, how can I fix this so I don’t have to reload my whole page to upload another file.
Thanks
Stickman on October 24, 2005
Interesting idea. You’d have to step through each element, using removeChild() to get rid of it. Or you could use innerHTML, but I wouldn’t recommend it.
If I get a spare minute, I might create a clearElements() function.
Flyboy on October 24, 2005
ok, thanks
now even reloading the form doesn’t help, because the javascript variables still exist on the main page.
Javaholli on October 25, 2005
Great thing! Thanks…
I’ve made some changes for a nicer output (table).
In the example HTML I replaced the tag with the following code:
In the multifile.js file I’ve added/changed the following lines:
var new_tr = document.createElement(“tr”);
var new_td_filename = document.createElement(“td”);
var new_td_button = document.createElement(“td”);
// Set row value
new_row.innerHTML = element.value;
// Add button
new_td_button.appendChild( new_row_button );
new_td_filename.appendChild(new_row);
new_tr.appendChild(new_td_filename);
new_tr.appendChild(new_td_button);
// Add it to the list
this.list_target.appendChild( new_tr );
Important thing is that the ’s are added to the tbody tag! It won’t work if you’re not using the tag. Took me a while to figure that out…
dan on October 31, 2005
how do i actually pass the value over to my asp page?
Execute on October 31, 2005
Hello, very nice code, isorta skim read the code after downloading, but i found this using AJAX search in google, obviously so did others who left angry comments
.
My question is, can you make an example of AJAX submitting the form? I have been having trouble submitting “file” inputs thru my AJAX script, I tried using the .value of the file input but it doesnt send it to the php script. How can i get the “Value” or the “file” itself with JS to send to PHP? any ideas?
Stickman on October 31, 2005
Execute: you can’t upload files via XMLHTTPRequest. Simple as that.
However, as I think has been mentioned above you could use a hidden iframe. I’ve done it myself and it works, but it can be a bit of a pain to get it working reliably.
Execute on October 31, 2005
ok… yea i found that out after a little bit of reading afteri posted that comment. thats a shame… However I did use an iframe, and just did target=’iframe’, and it works out fine… but what do you mean “bit of a pain to get it working reliably”, was way easier than i thought. Is there something else you were thinking of?
But still im amazed your script works in all these browsers, i havent tested with opera, or ie, but with firefox 1.07 works fine
. And i easily set it up without any hassle, so seriously great job, and i will include your comment etc and wont remove it ;P.
Happy halloween from DesignPlanet.biz
Stickman on November 1, 2005
Thanks for the flattery — always appreciated
For more info on the trials I had with uploading with iframes, see this entry.
DisasterMan on November 1, 2005
Found the script very easy to get working, and have used it to great effect. Thank you very much!
vanaja on November 3, 2005
Thanks for wonderful script.
Can any one tell me how to create a space in between the path and button?
i am new to programming.
Emmerson Miranda on November 4, 2005
Excelent work, It do all I need.
Good luck!!!
Robert on November 6, 2005
This is very smart and cool.
But….what is “Ajaxian” about this ?????
I don’t see no XMLHttpRequest calls.
Somebody please tell me
Robert on November 7, 2005
Re my comment above:
Just want to clarify -
STICKMAN did not call it AJAX in any way.
I was referring to those other stupid blog posts calling it “AJAX” – fawking idiots
Robert on November 7, 2005
>>Flyboy Says:
>> After uploading the files (done through ajax, so the upload
hmmm you sure you did thru XMLHTTPRequest ?
Care to share with us how you did it ?
Execute on November 8, 2005
Use iframes. because YOU CANT send files through javascript. I been lookin all over for a way to do it with the XMLhttpRequest rather than iframes. So you just simply target the iframe which is on top of your form, make it invisible with css and you got yourself a fake-ajax system
Robert on November 8, 2005
^^^^ so “FlyBoy” is full of BS ?
Stickman on November 8, 2005
Calm down, Robert. Clearly, for some people, Ajax has become a catchall term for a variety of newer browser technologies. While that might not tie in with the strict meaning of the term as it was originally intended, I don’t think it’s necessary to be quite so pedantic about it.
Fabian on November 9, 2005
Heyho, just wanted to say thanks for this great Widget…
It’ll help me in developing a FileBrowser-Servlet
ahussam on November 10, 2005
Hi, I am having some trouble with actually uploading the files in the backend, i tried a “stupid” approach to understand the logic, added 4 files, removed the 3rd the submit, used file_1 as static filename, then file_2…etc, it did not recognize file_2 although i removed the 3rd file !?
also i need to know (as a concept) as I use CFML, how would I transform the number of files and the filenames to the backend, i know how to do that on 1 file, but i just can’t understand the logic here for multiple files
thanks
Tbolt on November 12, 2005
Need to add a function that clears all onSubmit or whatever. Anyone set this up already? Otherwise you have to manually delete them out if you want to add more files.
Otherwise, it’s a great little script.
thanks
Shawn on November 12, 2005
For those still needing a file upload script – I offer up a starting point.
Yes, a starting point. This script solely handles file uploads and nothing else. You are responsible for securing your user’s input – I simply can’t do that for you, nor can anyone else.
http://www.top-frog.com/files/scripts/upload_sample.phps
Feel free to use the script or modify it in any way. For more information on handling file uploads in PHP you can refer to these pages:
http://us2.php.net/manual/en/features.file-upload.php
http://us2.php.net/manual/en/security.variables.php
JD on November 13, 2005
Great tool….this is the simplest multi-upload tool that I have seen.
I have a question…Is it possible to retrieve the number of file elements on the page at any given time? I am trying to send the “file count” in a hidden form field so that I know how many files to process on the server side.
Any help is appreciated.
Thanks for the work Stickman…….
Ulrich Fuchs on November 14, 2005
Hello!
I copied the 2 script files in /catalog/, and inserted your code in my contact form.
When I change input type to “image”, then I get an error – if I let it be as “file”, I can see the dialog, select pictures, but they will not be attached to the mail!!
Please help me and explain what to change if I want that IPG and PNG pictures can be attached – but no DOC, PPS and such stuff.
Thanks!
prince on November 14, 2005
ur script seems to be very useful…Stickman……can u make an image preview for uploading images.then it would be much useful.and also validate the image dimension,image type,etc….like the following one:
http://www.reallycoolspace.com/upload.html
http://www.reallycoolspace.com/upload.js (the js file, the html file links to this)
but this script doesnt work in all browsers.plz rectify it thru ur script….
Flyboy on November 15, 2005
Just back from a holiday and euhm, no, I’m not full of BS
You surely can upload files through javascript.
Problem is I wanted a status bar with it, had no time to do it all in ajax, so now I ended using 1 iframe, just for the status bar, will try and change that shortly too.
Now my only need is the function to clear out all the variables instead of having to do it manualy every time.
David Levin on November 15, 2005
Awesome tool! Great work!
Magic on November 15, 2005
Hi all. i tried that script at firefox 1.0.7. it does not works. it upload only one file. other selected files not uploads.
dpinto on November 16, 2005
Can you add a feature that checks if the same file is added twice in the list and alerts the user that he already has added that file once.
Overall its a nice script.
dpinto on November 16, 2005
Also that delete button could be an HTML link.
dheeraj on November 23, 2005
hi,
Thanks for your usefull code for multiple file upload…but I need that the file dialog box must be hidden… and instead of it their should be a link “upload files” just like GMail file attachment.
I have tried it but i have to click submit button 2 times to submit the files..
Pls give me a solution for that..
Mitt on November 23, 2005
First off, great job! Second for those of you who have asked about the image preview, I wanted the same thing but found that Firefox will not allow the image preview to work because it is a security feature to disallow linking or access to local files. I was able to make it work in IE but ened up leaving it out all together because I don’t like to restrict users on a browser they have to use.
Scaramouch on November 25, 2005
First off, great script. You’ve “thunk” outside the box a bit & come up with what i think is a very good approach to this. Now if i can only figure out how to use is in a .NET environment.
Does anyone know how i might be able to grab the files once they’ve been uploaded? Typically, i’d use the <asp:FileUpload> control, or even just something like <input type=”file” id=”file_1″ runat=”server”> (note the runat=”server” property) so that the control can be referenced server-side by it’s id. However since the file elements are being added client-side this approach won’t work.
I’d love to be able to use this script in my webform if I can.
Any help would be appreciated. Thanks.
Stewart Boutcher on November 26, 2005
I can verify that this script does not work in Firefox 1.0.7, either with file input naming convention “file_0″, etc or with “userfile[]“. In all cases only the first file is ever uploaded.
Mir Ai on November 28, 2005
Hi Everyone,
Very, very cool solution to uploading multiple files.
My requirements are a little different. I don’t want the user to see the file input files (text field or browse button). I want to be able to show a link which says “Add File”. I’ve tried hiding the ‘my_file_element’ field and then adding a link on the page which calls the following method:
// adds a new file
function addFile() {
var myUploadField = document.getElementById(‘my_file_element’);
if (myUploadField != null) {
myUploadField.click();
}
}
This “sort of” works. Clicking the links adds the file and then shows the uploaded file name in the list. However, it adds more file upload fields to the screen and when I try to remove an uploaded file, it gives me a javascript error. The form also does not want to submit the first time. I have to click the submit button a second time.
Any ideas or thoughts on how to make this work?
Thanks,
Mir
Shawn on November 28, 2005
Well, the script works fine with Firefox 1.0.7 on Mac. So I’d venture to guess that there is something wrong with the usage for the complaint that it doesn’t work on FF 1.0.7
®@T@Ø on November 28, 2005
How I can restrict the type (s) of archives for upload?
In the javascript, not in PHP. Something of this type was thinking about using substr to only catch the extention of the value of input file, but I did not obtain…
Sorry my english, I´m brazilian…
I´m waiting a return!!!
;º)
Joe Shelby on December 3, 2005
It works fine for me on Firefox 1.0.7 for Windows and IE 6, using JBoss/Tomcat/Struts/LazyDynaBean for the server side.
I hacked at it a bit. We needed to associate a description with the file as part of the app i’m using it in, so I added a callback feature along with some additional references. diffs are bolded below:
function MultiSelector( list_target, max, handler ){
…
// Is there a maximum?
if( max ){
this.max = max;
} else {
this.max = -1;
};
// Is there a callback?
this.callback = handler;
…
element.onchange(): add the new if
// Hide this: we can’t use display:none because Safari doesn’t like it
this.style.position = ‘absolute’;
this.style.left = ‘-1000px’;
if (this.multi_selector.callback) {
this.multi_selector.callback(this, “added”);
}
};
…
this.addListRow(): add new_row as a reference so callback can manipulate it.
// References
new_row.element = element;
element.new_row = new_row;
…
a demo callback:
function additionalAttachmentsCallback( element, action ){
if (action == ‘added’) {
element.new_row.appendChild(document.createElement( ‘br’ ));
var t = document.createTextNode(“Description:”);
var new_row_description = document.createElement( ‘input’ );
new_row_description.type = ‘text’;
new_row_description.value = ”;
new_row_description.size = 60;
new_row_description.name = “desc_” + element.name;
element.new_row.appendChild(t);
element.new_row.appendChild(new_row_description);
}
}
and now in addition to getting file_0, my struts action can look for a desc_file_0 for the description.
Wing on December 7, 2005
This isn’t an example of AJAX. It’s just manipulating the DOM using Java.
Where’s the advanced javascript and xml?
Stickman on December 7, 2005
You’re absolutely right. Please see the numerous, similar comments above.
aparch on December 16, 2005
Oh
thanks for your help.
I will come here sometimes for it.
Shrimp on December 18, 2005
Wow, I see the trackbacks have caused a rather large headache for the author
. I too found this page looking for AJAX information (via Google).
Don’t really have anything to comment on this script about, but Stickman, I feel your pain
. People would do well to read the comments and trackpacks before ripping into the author.
Oliver on December 21, 2005
Hi Folks
First of all;
Thank you for publishing this great and neat script!
I got it work with a GET request ‘only’ but would rather prefer to send the FORM by a POST.
Does anybody else face this issue or could me explain a work arround?
Oliver
Oliver on December 22, 2005
Hello All
I figured out, that I doesn’t work with FireFox but InternetExplorer.
If anybody found a workarround for FireFox, I’d very appreciate to learn about.
Btw. You may wish to see my modifications here: http://www.planetdoom.ch/test/upload_test.php
Regards
Oliver
lanner on December 23, 2005
hello,
can you explain to me what you put here :
action=”your_script_here.script”
i’m not understand about this, thanks a lot
zaila on December 28, 2005
i have try your code. When i save using “.html”, its work. But, when i save using “.htm”, it doesn’t work. can i know why and how to solve it.
Sourabh on December 28, 2005
sure it is a real nice way to upload multiple files. but as we have an option of zipping the stuff. this would defeat the idea of having the limit to upload. but sure, it can extend to any limit of uploading..
keep going….. !!
Mohammad on January 8, 2006
can anyone tell me in detail that if i chose four image files then ho i and where i go get the valuse to put in my mysql server i am bit confussed please please Help if you can write me a two line of script of insert that would be great i can feed off of that but its a great script very nice hats off to you man but with little more help for novice like me can solve the problem for lots of us out thee how they are trying to learn a thing or two.
James on January 17, 2006
Well, the script works fine with Firefox 1.0.7 on Mac. So I’d venture to guess that there is something wrong with the usage for the complaint that it doesn’t work on FF 1.0.7
Eric Kaiser on January 24, 2006
Great script! I’m about as stupid as it comes to stuff like this. I was in search of an inclusive script that not only allowed multiple selection of files to upload, but I wanted it to upload as well. Some of the upload examples on this forum don’t make sense, or are incomplete. I hope to post a change to that. By surfing other sites I came up with a vare bones PHP upload script you can put on your page. There is no resizing of the files or file checking, but I’m sure I will get that going real soon. If anybody wants that feel free to email me.
Here’s the PHP code that uploads the files:
foreach ($_FILES["file"]["error"] as $key => $error) {
echo “key: “.$key.”";
if ($error == UPLOAD_ERR_OK) {
$tmp_name = $_FILES["file"]["tmp_name"][$key];
$name = $_FILES["file"]["name"][$key];
move_uploaded_file($tmp_name, “tmp/”.$name) or die(‘upload error’);
}
}
I made one change to the multifile.js script. Look for the line that reads:
element.name = ‘file_’ + this.id++;
This is currently around line 65, and change it to:
element.name = ‘file[' + this.id++ + ']‘;
I’m submitting my form onto itself. I have not tested this script if your form action goes to another page.
Thanks again for this script.
Rich S Wyatt on January 24, 2006
Hello Stickman! Great work.
I’m using this in an intranet and have a couple of questions.
#1 – I would like to modify the output to include some additional text after a file is selected. Right now it simply states the path to the file on the local machine. I’ve played with some pieces of the code to no avail. Can you point me to the line that would allow me to add some things to the path on display?
For example: Image 1: U:\MyPath\MyImages\bobspic.jpg
Secondly – when an administrator browses the administration page for a section that may already have some images uploaded:
Is it possible to recreate what you are doing dynamically with the images that already exist? That way I can “Delete” images that are no longer needed and then catch that all with PHP on the submit of my form.
Thanks, in advance, for any insight you may give and again: great work!
Steve Owen on January 26, 2006
Great script, but there does appear to be a bug (feature?) in Firefox. I’ve only tested it in Firefox and IE, and it’s fine in IE, but in Firefox, if you have the script in a table, but the form is outside of the table cell, the new File elements, as they are created, are not assigned to the form. This can be tested by asking the script for the form name of the new element (“undefined”) or keeping count of how many form elements there are (it doesn’t go up). This is almost certainly Mozilla’s unforgiving nesting of tags, and is fair enough, but you do need to watch out for it.
As an example, in the test page in the zip, put the form name after a table tag but before the tr tag. Submit the form with more than one file and only the first one is uploaded.
It’s driven me mad for a few days trying to track this down, so I’d spare anyone else the pain.
Stickman, great script. Thanks.
Steve Owen on January 26, 2006
Oh, as a follow-up, if anyone’s interested in mods, I’ve added to the script to also just show the filename rather than full path, and to put the Delete button at the start, just as an “X”. It means it all lines up and, I think, looks a lot nicer. You could of course style up the button to make it look even better.
Because of the innerHTML being affected by putting the button first, you need to put it in its own element. So here’s part of the new script, the this.addListRow function…
/**
* Add a new row to the list of files
*/
this.addListRow = function( element ){
// Row div
var new_row = document.createElement( ‘div’ );
// Delete button
var new_row_button = document.createElement( ‘input’ );
new_row_button.type = ‘button’;
new_row_button.value = ‘X’;
// References
new_row.element = element;
// Delete function
new_row_button.onclick= function(){
// Remove element from form
this.parentNode.element.parentNode.removeChild( this.parentNode.element );
// Remove this row from the list
this.parentNode.parentNode.removeChild( this.parentNode );
// Decrement counter
this.parentNode.element.multi_selector.count–;
// Re-enable input element (if it’s disabled)
this.parentNode.element.multi_selector.current_element.disabled = false;
// Appease Safari
// without it Safari wants to reload the browser window
// which nixes your already queued uploads
return false;
};
// Set row value
var c = element.value.lastIndexOf(‘\/’); //For Unix, etc.
if (c != -1)
html = element.value.substring(c+1);
else {
var c = element.value.lastIndexOf(‘\\’); //Win
if (c != -1)
html = element.value.substring(c+1);
else
html = element.value;
}
// Add button
new_row.appendChild( new_row_button );
var new_row_text = document.createElement( ’span’ );
new_row.appendChild(new_row_text);
new_row_text.innerHTML = ‘ ’ + html;
// Add it to the list
this.list_target.appendChild( new_row );
};
I also liked to change the size and class name of the Browse button, which you can add by expanding the MultiSelector object:
function MultiSelector( list_target, max, class_name, browse_size ){
and after this.max = -1, these changes:
this.max = -1;
};
this.class_name = class_name;
this.browse_size = browse_size;
/**
* Add a new file input element
*/
this.addElement = function( element ){
// Make sure it’s a file input element
if( element.tagName == ‘INPUT’ && element.type == ‘file’ ){
// Element name — what number am I?
element.name = ‘FILE’ + this.id++;
element.className = this.class_name;
element.size = this.browse_size;
// Add reference to this object
element.multi_selector = this;
I hope these additions are useful.
Nate on January 27, 2006
Man, this script works great in all of the browsers -I-, but not in the one browser my company (and subsequently, some of our customers) use!
Sadly, we’re stuck in the stone age with IE 5.x Mac, and it doesn’t seem to work at all. When I browse/add a file, the file name just sits in the field and doesn’t go anywhere, nor does it appear in the listing below.
I know I’ve had trouble with CSS in this version of IE, but it mostly had to do with using quotes in url() options, and the classic box-model problems. Since the filename seems to hang in the field, I’m guessing it’s a JS-related issue, and not CSS.
This makes me sad, because this is the _perfect_ solution to some of our problems. Our customers upload a lot of files to us on a daily basis, and this is so much cleaner than 10 file/browse lines.
Thanks in advance for any hints
Arminda on January 28, 2006
Hello,
can someone help me with uploading the file(s) using the hidden iframe, so that i can upload at the same as i insert the file?
Execute: ” However I did use an iframe, and just did target=’iframe’, and it works out fine..”, can you show me? I don’t understand?
Stickman: “However, as I think has been mentioned above you could use a hidden iframe…”, can you?
Thanks.
Chris on January 31, 2006
Hi, Just have a quick question. I’m using IE 5.5. I use css for my input fields. On my text input fields I have a border on all four sides. When the page initially loads the border is around my text window but after the first click on the browse button and selecting a file the css disapears and I just have a empty space where the text button should be. It’s still there, just no borders. Any idea how to keep the css?
Thanks
Chris on January 31, 2006
I figure it out.
In you .js file under -
element.name = ‘file_’ + this.id++;
add
element.className = ‘formInputs’; // or what ever class your text input is
This will pull any class you’ve assigned to the input fields objects and apply it to the new input field object that gets created by the js file.
You can also do this for the delete button,
find the following
new_row_button.value = ‘Delete’;
add this after
new_row_button.className = ’submitbutton’; // or what ever class your submitbutton are
Thanks for the great script.
Tj on February 4, 2006
Hey everyone, is anyone having problems with the files uploading in IE? It’s not working for me… It works just fine and awesome in FireFox, but IE wont upload the files…
Thanks for any help!
-Tj
Ben on February 9, 2006
Hi, thank for the useful script. I’ve made some changes for a nicer output (table).
In example.html, changes line <div id=”files_list”></div> to <table id=”files_list”></table>
In multifile_compressed.js, changes function addListRow as follow:
this.addListRow = function( element ){
// Row div
var new_row = document.createElement( ‘tr’ );
var new_col_filename = document.createElement( ‘td’ );
var new_col_button = document.createElement( ‘td’ );
new_col_filename.setAttribute( ‘align’, ‘left’);
new_col_button.setAttribute( ‘align’, ‘right’);
// Delete button
var new_row_button = document.createElement( ‘input’ );
new_row_button.type = ‘button’;
new_row_button.value = ‘Delete’;
new_row.appendChild( new_col_filename );
new_row.appendChild( new_col_button );
// References
new_row.element = element;
// Delete function
new_row_button.onclick= function(){
// Remove row from table
this.parentNode.parentNode.parentNode.removeChild(this.parentNode.parentNode);
// Remove element from form
this.parentNode.parentNode.element.parentNode.removeChild( this.parentNode.parentNode.element );
// Decrement counter
this.parentNode.parentNode.element.multi_selector.count–;
// Re-enable input element (if it’s disabled)
this.parentNode.parentNode.element.multi_selector.current_element.disabled = false;
// Appease Safari
// without it Safari wants to reload the browser window
// which nixes your already queued uploads
return false;
};
// Set row value
//new_row.innerHTML = element.value;
new_col_filename.innerHTML = element.value;
new_col_button.appendChild( new_row_button );
// Add it to the list
this.list_target.appendChild( new_row );
};
Hopeful that will help some one.
Kelly on February 15, 2006
Help!, Updated my mozilla and now this multifile uploader wont work!!!
Steve Owen on February 15, 2006
Ben’s table code is excellent, but doesn’t actually work in IE. Or rather, isn’t DOM-compliant. (And it’s ironical that IE is the browser that doesn’t like its lack of compliance.)
Instead, you want to append the child to a element. It’s a simple change. Where you replaced <div id=â€files_listâ€></div> with <table id=â€files_listâ€></table>, you should actually replace <div id=â€files_listâ€></div> with <table><tbody id=â€files_listâ€></tbody></table>
Cheers,
Steve
PS, That has got to be the most annoying “security code” I’ve ever seen. It always takes about four goes and several refreshes to actually work out what it says.
Steve Owen on February 15, 2006
Sorry, that last comment should have read:
“Instead, you want to append the child to a <tbody> element.”
Jesse H on February 17, 2006
Here is vb.net back end implementation after the page is submitted. Someone was asking for it.
‘get the form file collection
Dim myfiles As System.Web.HttpFileCollection = System.Web.HttpContext.Current.Request.Files
Dim iFile As Integer
For iFile = 0 To myfiles.Count – 1
‘ get the posted file
Dim postedFile As System.Web.HttpPostedFile = myfiles(iFile)
‘make sure it is not blank
If Not postedFile.FileName.Equals(“”) Then
‘Save File to the proper directory
postedFile.SaveAs(Request.MapPath(“folder/”) + System.IO.Path.GetFileName(postedFile.FileName)
End If
Next iFile
Jonny on February 20, 2006
Perfect. Thank you very much for making the script available.
Mark on February 21, 2006
I want to load several hundred webpages to my typepad blog… can anyone recommend a good program for this? Please email me, thants
Mark on February 21, 2006
What’s the best telnet program and can they be used on blogs such as typepad?
http://information.typepad.com
Jorge on February 21, 2006
Greatfull
Cade on February 22, 2006
what is the best php for upload with multiple-file???
Can i use this file so i want or exist a coopyright(by the way i don’t said that it’s my code)?
Stickman on February 22, 2006
Rather than post my own code for handling the upload at the server end, I’ve left that up to you. There are plenty of good tutorials out there that deal with this — for example, look at this look at this comment or check Google.
As for usage, you are free to make use of the code in any way you like, although I would appreciate it if you left the copyright information in the file.
Rich on March 7, 2006
This script is perfect for what I need. Thanks!
One little problem – it works great the first time, but if I go back to the page, it’s almost like the script has disappeared. When I select a file via the browse button, it doesn’t update the file list, and doesn’t create a new and empty control. I can only upload one file from then on.
I’ve tried it both Firefox 1.5 and IE 6 and they both act the same. It looks like the DOM is setup properly the second time around, so I’m a bit stymied.
Any suggestions? I’m using java and struts.
duh on March 7, 2006
Looks like http://www.ibulc.com
Rich on March 7, 2006
regarding my “doesn’t work the second time post”:
Turned out that I wasn’t resetting the form correctly.
Bleeding Edge on March 9, 2006
Looks like IE 7 beta 2 (7.0.5296.0) has a little trouble with this code. It doubles up the elements once a file has been selected. Has anyone else experienced this problem? Has anyone created a fix for this? I will try to look into it more and see if I can find a fix. I’ll keep you posted.
Andy on March 10, 2006
Nice script, Stickman. I was hoping you or somone else could help me fine tune it to my needs.
What I’m trying to do is give the user another input box in which to enter a title for the file and then have that title display (instead of the filename) after the user has clicked an “Add to Queue” button (as opposed to displaying immediately after they’ve finished browsing, as the script does currently).
This is what I’ve tried so far:
function addFile(){
var multi_selector = new MultiSelector( document.getElementById( ‘files_list’, 5 ) );
multi_selector.addElement( document.getElementById( ‘my_file_element’ ) );
}
Title:
File:
Add
Files:
I tried to trigger the display of the filename by using an onclick call to a function containing the instantiation of the MultiSelector class. I can’t figure out why this won’t work. Any help would be greatly appreciated.
Thanks a lot!
Andy on March 10, 2006
Crap. Your wysiwyg took that a little too literally. Here’s an attempt to re-post my code. I had to replace “” signs to get it to display, thus all the \’s. I hope it’s not too hard to read. Thanks again!
function addFile(){
var multi_selector = new MultiSelector( document.getElementById( ‘files_list’, 5 ) );
multi_selector.addElement( document.getElementById( ‘my_file_element’ ) );
}
Title: \\input type=”text” name=”title_1″\\
File: \\input id=”my_file_element” type=”file” name=”file_1″\\
\\a href=”javascript: void(null);” onclick=”addFile();” class=”buttons add”\\Add\\/a\\
Files:
\\div id=”files_list”\\ \\/div\\
Bleeding Edge on March 12, 2006
IE7 beta 2 fires the onchange event twice when you select files using the browse button. Once when a files has been selected. And then once more when it looses focus.
Blocking the onchange event once it gets executed fixes the problem.
Changing the code as seen below puts a bandaid on it so it works in IE7 (it also still works in Firefox 1.5).
// What to do when a file is selected
element.onchange = function(){
if (!element.block)
{
element.block = true;
// New file input
var new_element = document.createElement( ‘input’ );
new_element.type = ‘file’;
// Add new element
this.parentNode.insertBefore( new_element, this );
// Apply ‘update’ to element
this.multi_selector.addElement( new_element );
// Update list
this.multi_selector.addListRow( this );
// Hide this: we can’t use display:none because Safari doesn’t like it
this.style.position = ‘absolute’;
this.style.left = ‘-1000px’;
}
};
Rob Mitchell on March 16, 2006
Hi – I’m using your script with IE 6.0.2900.2180.xpsp_sp2_rtm.040803-2158 on Windows XP Pro SP2 and results in a Javascript error when trying to submit the form with Access is denied. Any ideas?
Thanks!
Rob
rob@baseclasstech.com
vic on March 20, 2006
Hi,
I got a problem with uploading the files:
I used Shawn Parkers upload script-> http://www.top-frog.com/files/scripts/upload_sample.phps
But when I try to upload I get this error:
Warning: move_uploaded_file(C:/Program Files/xampp/htdocshttp://localhost/restricted/upload/uploads/tyson_4.jpg) [function.move-uploaded-file]: failed to open stream: Invalid argument in C:\Program Files\xampp\htdocs\restricted\upload\upload.php on line 119
Warning: move_uploaded_file() [function.move-uploaded-file]: Unable to move ‘C:\Program Files\xampp\tmp\php11.tmp’ to ‘C:/Program Files/xampp/htdocshttp://localhost/restricted/upload/uploads/tyson_4.jpg’ in C:\Program Files\xampp\htdocs\restricted\upload\upload.php on line 119
Does anyone has an idea what’s wrong?
regards,
Vic
Neil on March 29, 2006
(tip for beginners)
In PHP this is a good starting point for handling the files
echo ‘<pre>’;
print_r ($_POST);
print_r ($_FILES);
echo ‘</pre>’;
Just shows you what you’ve got after the submit.
Lito on April 6, 2006
This is a added to check if the file all ready exists in the list:
element.onchange = function () {
var files = this.parentNode.getElementsByTagName(‘input’);
var existe = new Array();
for (var i=0; i 1) {
return false;
}
}
}
Steven on April 7, 2006
Great Script. Got some problem with it though. I use firefox, php to generate the javascript.
page1: the multiselector, works fine, no errors, shows the fullpath of the file.
-submit the form to page2-
page2: php receive the variable file_”id” as a filename only, instead of the fullpath of the file.
Anyone else got this kind of problem? Any help would be great.
Cheers
Anilal on April 7, 2006
Wonderful file upload component.
Could some one help me how we can get the files in the backend ASP so as to upload it.
What will be the File name(s)? any idea or code ..appreciated
Anilal
Craig on April 8, 2006
Would it be possible to add all of the file elements to a single array? My php upload class (Easy PHP Uploads) expects an array like…
_FILES: Array
(
[upload] => Array
(
[name] => Array
(
[0] => FETall.jpg
[1] => gan_multiplot.plt
[2] => will-look-up_0_97.zip
)
[type] => Array
(
[0] => image/jpeg
[1] => application/octet-stream
[2] => application/octet-stream
)
[tmp_name] => Array
(
[0] => C:\WINNT\php59B.tmp
[1] => C:\WINNT\php59C.tmp
[2] => C:\WINNT\php59D.tmp
)
[error] => Array
(
[0] => 0
[1] => 0
[2] => 0
)
[size] => Array
(
[0] => 46676
[1] => 6713
[2] => 33271
)
)
)
Thanks for any advice. I’m no js expert, but with a drawing can probably figure it out.
Cheers.
Melissa on April 8, 2006
This was quick and easy! You save my time without having to code and look elsewhere. Thanks.
Craig on April 8, 2006
My appologies this was answered in comment XXXII.
hint: element.name=’upload[]‘; // d’uh!
thinsoldier on April 10, 2006
in safari the limit of 3 files is not obeyed.
And your security code is really hard.
Andrew Bulmer on April 11, 2006
Not sure if anyone checks this page, but I found a small bug in this. If you click browse twice to bring up 2 file selectors at once and then select a couple of files, one of them can’t be deleted. It throws an error on the following:
this.parentNode.element.parentNode.removeChild( this.parentNode.element );This is because when you open the second selector it tried to remove it twice. I think you might want to do something like this inside the element.onchange function (in addElement):
this.onchange = function ()
{
this.multi_selector.addElement (this) ;
this.multi_selector.addListRow (this) ;
} ;
I’ll have to do some testing to see if that works on the submit side of things
Andrew Bulmer on April 11, 2006
Well it seems it wasn’t as simple as I first thought. But I do have a solution… I just made the onchange event update the row. To do this I had to make addListRow return the DOM node of the list and add a textnode instead ofusing innerHTML. I also had to make a refernce to the text node and the delete button in the DOM node. Here’s the code for addElement and addList node:
Hope this helps
stephen on April 13, 2006
great script. i have it working with classic asp. buzz me if you need src.
Fitz on April 16, 2006
I am using Coldfusion. Can someone give me an example of the backend for the multiupload. I have the front end with no problem but the back end I am not sure how to address after I submit to another page. All the examples are in php that I currently see. Any help is welcomed.
Thank you in advance.
Fitz
Fitz on April 17, 2006
I found the problem with my server end. It had nothing to do with the code it was actually firefox. The deal with having the form delcared within in a table was causing the problem Once I read the above post I found that the form had to be delcared above the table and all is well. For those few that are having to use coldfusion at their job and need this code here it is..
Could not upload file [#file.serverfile#]
“>
“>
Sorry for the crude formatting.
Fitz
Fitz on April 17, 2006
Ooops forgot about the special characters: See if this works better.
<cfloop from=”0″ to=”#lvMaxNumberFiles#” index=”iItem”>
<cfset filename = “form.File_#iItem#”>
<cfif isdefined(“#variables.filename#”)>
<!— Handle the Pictures\All Folder first —>
<cfif evaluate(variables.filename) neq “”>
<cfset lvUploadOkay = “true”>
<CFTRY>
<cffile action=”upload” filefield=”#variables.filename#” destination=”#lvPicturesPath#” nameconflict=”unique”></cffile>
<CFCATCH TYPE=”Any”><cfset lvUploadOkay = “false”><CFOUTPUT><b>Could not upload file [#file.serverfile#]</b><br></cfoutput></CFCATCH>
</CFTRY>
<cfif isdefined(“lvUploadOkay”) and lvUploadOkay is ‘true’>
<cfset message = message & “#file.serverfile# was uploaded successfully<br>”>
<cfelse>
<cfset message = message & “#file.serverfile# was not uploaded<br>”>
</cfif>
</cfif>
</cfif>
</cfloop>
Luca on April 19, 2006
What do you think about adding this code to the UPLOAD SCRIPT with PROGRESS BAR in AJAX ?! at this site http://php5.bluga.net/progressDemo/demo.php
thanks
Luca.
Jesus on April 21, 2006
El código es genial, un excelente trabajo…
Thank you.
Tomaž on April 28, 2006
Very coll code, thanks.
Tomaž
hudz on April 28, 2006
Anyone know how to do it with Java-struts? …
Just email me and I will appreciate it very much, i will put credit on you.
hudz on May 2, 2006
I have trouble with downlisting the files. I have tried it for several days using java-struts and mozilla FireFox 1.5.0.2. It doesn’t seem to work. I haven’t alter the code, it’s a standard from the downloaded file. Also, what is exactly the function between these two files, multifile.js and multifile_compressed.js, I have read the comments but does not help me. Please Help.
hudz on May 3, 2006
hi all,
I have downloaded the files and implemented it at my code, but it seems doesn’t works. I used struts. and im totally new. This is my code
Please tell me what is lack in my code because it does not list down the files..
this is my email hudzna@gmail.com
Thank you..very much
derek on May 4, 2006
hudz, The compressed file is the same code, just smaller in filesize. Just makes your site load faster since there is a smaller download.
hudz on May 4, 2006
Thank you Derek,
I’ve noticed it..Sorry for posting a nonsense post. But, Currently I’ve tried to do it with struts but it seems to not working. I’ve posted my code above. Hope anyone can help me.
Thank you again..
mankind on May 5, 2006
alert(“Nice Work …..”);
[Stickman says: Hmm...embedding Javascript in a comment...testing for XSS vulnerabilities? I think maybe you need to read up a bit more on the topic first.]
hudz on May 9, 2006
in original :
input id=”my_file_element” type=”file” name=”file_1″ >
in my struts
html:file property=”attachment” size=”75″ />
where should I put name=”file_1″??
Ron W. Waatsveen on May 14, 2006
Is it possible to hide the tag?
I have an application with a Java applet that download a file to a spesific catalog on my lokal disk.
When im finished with my document I push a button that starts an applet who upload the file.
I dont like this method because its little bit slow and maybe a overkill.
I also want to say that the applet I use uploads several files at time. I can select a hole folder with files and upload them.
Dave on May 15, 2006
Hi,
has anyone used this yet for creating a mail feedback form that in the back-end (php based) mails the attached files? I would be looking for this. Until now I got stuck with pre-defining the number of possible attachments so for the front end this script would be great. Now I’m not so sure how to process the files in the back-end and mail them. Any?
Thx
Dave
David Scotti on May 18, 2006
Does not work in Netscape – and in this world – if it doesn’t work in netscape, then it doesn’t work at all!
david on May 21, 2006
Is anone able to give me a piece of code to completly rest the multiuploader? (delete all rows and hidden file input fields). I tried to do this for several hours but it did not work
Thank you,
david
derick on May 24, 2006
Great script. Doesn’t work in Konqueror, though. The file list doesn’t update.
power cord on May 25, 2006
Prasanna on May 30, 2006
Hai,,
Thank you for the Script it working fine .
Any AJAX based FTP component For c#.NET Development and ASP.NET Development.
Thank you..
R.Prasanna Vignesh
Sondre on June 2, 2006
Hi!
This looks like a great solution to me, but I’m simply not into coding… What am I to do with the files when I have downloaded them? Sorry if it’s a stupid question…
Frank on June 3, 2006
Was wondering if there has been any code fixes for the table code in one of the above posting. Primarily this one post :Comment by Ben | 02/09/06 at 3:38 pm . I cannot get it to see the tbody’s!! I have tried a bunch of things. Any help would be appreciated. Thank you.
dave on June 22, 2006
Very nice script.
I have added the following javascript script to prevent the user from uploading the same file more than once.
// Check to ensure same file is not uploaded more than once dhy
var files = this.parentNode.getElementsByTagName(‘input’);
var lastfilename = files[files.length-1].value
for (var i=0; i
dave on June 22, 2006
Ok, the web page online messed up previous post. I will try again below.
element.onchange = function(){
// Check to ensure same file is not uploaded more than once dhy
var files = this.parentNode.getElementsByTagName(‘input’);
var lastfilename = files[files.length-1].value
for (var i=0; i
dave on June 22, 2006
i
dave on June 22, 2006
element.onchange = function(){
// Check to ensure same file is not uploaded more than once dhy
var files = this.parentNode.getElementsByTagName(‘input’);
var lastfilename = files[files.length-1].value
for (var i=0; i
Craig J. on June 24, 2006
Has anyone written a Delete All function?
I’d like to add a button to remove all of the files that the user has entered but I am not sure how to properly remove all of the file elements.
Can someone help me with this?
Thanks
Craig J.
Lee on June 27, 2006
I was wondering if it would be possible to hide the ‘no file selected’ (in safari) message that the file input places on the form? I tried adding new_element.style.color = ‘#FFFFFF’; in the javascript, but the font colour didn’t change (the text colour in the file input box in firefox changed to white).
Anyone else have any ideas?
Jafo on June 27, 2006
To add a space before the delete key:
// Set row value
new_row.innerHTML = element.value;
Change to:
// Set row value
new_row.innerHTML = element.value + ‘ ‘;
Hisham Al-Beik on July 7, 2006
#1 – great code.. thanks for it..
#2- How to DELETE ALL…
(Stickman, you can implement it in your code if you like, just credit me, thanks, and if you are able to clean it up.. then please shoot me an email with the clean (uncompressed) code.) thanks..
Step #1 – I added two hidden fields.. to keep track of the ID of added rows and ‘hidden’ file inputs.
Step #2 – I edited the multifile.js so that everytime it adds a field and a row, it appends the hidden fields with their IDs seperated by a comma. (which we will need later to break them down into an array)
// Element name — what number am I?
ada = ‘file_’ + this.id++;
element.name = ada;
element.id = ada;
//Hide this: we can’t use display:none because Safari doesn’t like it
this.style.position = ‘absolute’;
this.style.left = ‘-1000px’;
document.getElementById(‘hidden_field_2′).value += this.id + “,”; // Delete All
Also, if you want you can put in the form tag within the onReset, so that when resetting the form it will also clear the file list..
any question email me at halbeik AT DONOTSPAM vicr DOT com (just remove the donotspam part and replace the rest with the proper characters….
######## Stickman, I can email you a copy of my edited example zip i downloaded from here.. and you can clean it up and host it.. just email me if you like….. (i’ll also include this message as a txt file.. i’ll have to clean it up with the line breaks and such… #########################
Hisham Al-Beik on July 7, 2006
Ok… so part of it didnt show up.. here is a link to a text file on how you can implement a DELETE ALL..
on a side note, one thing i added to this in my work, is a text input below each row of the file list, this is because the usage is to upload multiple images.. and i wanted to inclde a feature to add captions to each picture…. i think as long as you add anything within the div element.. it’ll get removed with the delete all… i havent tested yet, but will do tomorrow.. and put an update..
http://djhash.dockex.com/how-to-delete-all.txt
Hisham Al-Beik on July 7, 2006
Ok.. so the test was successful.. anything u put in the div, will get removed with the delete all function..
Have fun..
Jose Rodriguez on July 8, 2006
Hope this helps for the uploading part, the code only shows useful information…
it only let you upload gif and jpeg files.
<html>
<head><title>Results</title></head>
<body>
<?php
echo "Files sent<br>";
reset ($_FILES);
while (list ($clave, $val) = each ($_FILES)) {
if($val['type'] == "image/gif" or $val['type'] == "image/pjpeg"){
echo ‘<br>’;
echo "$clave => $val<br>";
echo ‘Name: ‘ . $val['name'].’<br>’;
echo ‘TmpN: ‘ . $val['tmp_name'].’<br>’;
echo ‘Size: ‘ . $val['size'].’<br>’;
echo ‘Type: ‘ . $val['type'].’<br>’;
echo ‘Err_: ‘ . $val['error'].’<br>’;
}
}
?>
</body>
</html>
Damon on July 13, 2006
Uhh, nice effort but.. don’t you think you’ve reinvented the wheel a bit with this? This has been done hundreds of times before.. the most popular probably being gmails method for attachments (which also uploads them as each gets attached so it feels lightning fast).
Damon on July 13, 2006
Also, forgot to mention that the spec allows more than one file per field (comma delimited IIRC). The vendors have just never implemented it. If they would you could Ctrl/Shift click to select multiple files in the file browser just like you can outside the browser.
Stickman on July 13, 2006
Damon: If you read the original post, you’ll see that the intention was specifically to avoid the ‘multiple file elements’ approach (as used by GMail, among others). Of course the end result is the same, but that’s not the point — it’s about presentation.
As for uploading files on the fly: you could do the same with this technique but I didn’t because again, that wasn’t the point. This was never supposed to be ‘the ultimate AJAX upload widget’, just a nicer way to present multiple uploads.
If I had more spare time, maybe I’d develop this to the nth degree — there certainly have been plenty of suggestions for improvements in the 180 or so comments so far. But for now I think of it as a nice little proof-of-concept — it’s up to the developer to decide what, if anything, to do with it.
Wenqi Dwyer on July 16, 2006
It appears the script doesn’t support maintaining the file list values upon refreshing of the page. Any work-around?
Kabelo on July 19, 2006
thanks for the code it seems to work,the proble i’m having is to insert those uploaded files to the database.can you help with the insert of those file.
Patrick on July 25, 2006
How would you handle this via php? The code works fine to upload my files as long as you don’t delete any files along the way. I give each upload box the name
element.name = ‘uploadedfile’ + this.id++;
Then in my php code I upload the file from the file box called uploadedfile1, uploadedfile2, etc. As you delete any files it still increments the element name and this causes me a problem.
I have a maximum of 12 files to upload so if you delete two files the last two uploaded file box names are uploadedfile12 (since numbering starts at 0) and uploadedfile13.
Anyone have any suggestions?
Ashok on July 27, 2006
Hi Plz send me code to attach multiple file in email using PHP..
Pablo on August 1, 2006
Hey! I’m a newbie! So please help me on this one!
I simple do not know how to get the selected files uploaded to my server!?
I’m using asp.net 2.0 and Visual Studio 2005…
Below i my code:
——————–
.ASPX
——-
Files:
var multi_selector = new MultiSelector( document.getElementById( ‘files_list’ ), 3 );
multi_selector.addElement( document.getElementById( ‘my_file_element’ ) );
.CS
——
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
public partial class Default2 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void Button1_Click(object sender, EventArgs e)
{
//‘get the form file collection
HttpFileCollection myfiles = System.Web.HttpContext.Current.Request.Files;
for(int iFile = 0; iFile
Pablo on August 1, 2006
Hmm…I do not know what happen before…my message got pretty f…..? why? posting too much…
Hey! I’m a newbie! So please help me on this one!
I simple do not know how to get the selected files uploaded to my server!?
I’m using asp.net 2.0 and Visual Studio 2005…
Below is my code:
——————–
.ASPX
——-
Files:
var multi_selector = new MultiSelector( document.getElementById( ‘files_list’ ), 3 );
multi_selector.addElement( document.getElementById( ‘my_file_element’ ) );
and – see next message…
Pablo on August 1, 2006
.CS
——
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
public partial class Default2 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void Button1_Click(object sender, EventArgs e)
{
//‘get the form file collection
HttpFileCollection myfiles = System.Web.HttpContext.Current.Request.Files;
for(int iFile = 0; iFile
Aalok on August 2, 2006
Jesse H gave this code for vb.net .
Here is vb.net back end implementation after the page is submitted. Someone was asking for it.
‘get the form file collection
Dim myfiles As System.Web.HttpFileCollection = System.Web.HttpContext.Current.Request.Files
Dim iFile As Integer
For iFile = 0 To myfiles.Count – 1
‘ get the posted file
Dim postedFile As System.Web.HttpPostedFile = myfiles(iFile)
‘make sure it is not blank
If Not postedFile.FileName.Equals(—) Then
‘Save File to the proper directory
postedFile.SaveAs(Request.MapPath(â€folder/â€) + System.IO.Path.GetFileName(postedFile.FileName)
End If
Next iFile
Dear sir ,
When i am using this code on button click for final submit . then it’s give nothing.
When i am tracing
Trace.Warn(“myfiles counter”, myfiles.Count)
thein it gives count “0″. Means no file collection now what can i do please reply as soon as possible .
one thing –
in form collection it show’s all files which i am uploading .
now boll in ur hand .
With regards
Aalok Kumar Yadav
Aalok on August 2, 2006
isolve out my problem
raduen on August 3, 2006
I wonder if it;s possible to put a sort of grid lines in de file list div with file size en mod date. those last two are not that important.
ps: i have the file list div in a tbale
upload file on August 3, 2006
Very nice post.
About file hosting, i usually use yoUpload.com to upload all my files. I believe that is the best, but it’s my opinion, ehehe…
http://www.youpload.com
Thanks,
Robert
John D on August 4, 2006
Hi,
I was wondering if it was possible to have a check box or a text box associated with each file upload. I mean this script is great in that it allows you to upload multiple files through a single element, but how can i upload multiple files AND information associated with them (as entered via a checkbox or text box next to the file input)????
Any ideas? I was able to get your code to work beautifully as is, but how can i add this functionality? Please keep in mind that i am a newbie and am very unfamiliar with coding in javascript (i work mainly with PERL)
THANK YOU!!!!!
teo on August 9, 2006
I’m able to implement this inside my jsp here. But the only problem is how do I pass all the attach files to a single property in sturts? And how do I get all the attach files inside the action class? Hope someone would help on this. Thanks.
Chris Coleman on August 9, 2006
For everyone having issues actually uploading more than one file, here is the solution! The error is due to the face that “createElement” objects are attached to the “document” but are not attached to the form you are submitting. So, only the original element transfers. To correct this:
1. Assign an ID tag to your form, e.g.
<FORM ID=\”YOUR_FORM_ID\”>
2. Add the bold line of code to your .js file (just before the lines to change this.style.position and this.style.left:
document.getElementById( ‘YOUR_FORM_ID’ ).appendChild( this );
Well, I hope that helps everyone. Good luck and email me if you have any further questions!
jimy on August 17, 2006
Perfect script, Stickman. Thank you very much for making the script available.
Jonhoo on August 18, 2006
WoW, great script!
Just one thing I’ve noticed:
I think you can use visibility:hidden to hide the input fields instead of using
this.style.position = ‘absolute’;
this.style.left = ‘-1000px’;
Not sure yet though…
Stickman on August 18, 2006
Jon: The positioning hack is to fix a a problem with Safari, which ignores form elements that are hidden.
Jonhoo on August 18, 2006
Are you sure that applies to visibility:hidden as well?
visibility:hidden has always worked for me, even though display:none haven’t..
Stickman on August 18, 2006
The ‘display’ and ‘visibility’ properties aren’t the same: if you set ‘display:none’ then the element is completely removed from the page flow, whereas ‘visibility:hidden’ just hides the element — ie. you get a gap where the element was. So it isn’t really suitable.
Jonhoo on August 18, 2006
Ah, rigth
Learn something new every day ^^
GREAT script by the way.
Jonhoo on August 21, 2006
There is a problem with the script regarding getting the files after you’ve pressed submit, it is the following:
Usually, if the user does not press the delete button at any time, we can use a for loop to get the information as such:
for ($file = 0; $file
Jonhoo on August 21, 2006
for ($file = 0; $file
Jonhoo on August 21, 2006
Hmm, code doesn’t seem to work…
I’ll try to explain with an image:
Usual file array with max 3 files:
file_0 = First file
file_1 = Second file
file_2 = Third file
If the user presses delete on the second file, however, and then adds another one, the array will be as such:
file_0 = First file
file_1 = Empty
file_2 = Third file
file_3 = New Second file
Is there a way to get around this so we won’t have to resort to the much slower foreach loop, and check if each file has in fact been downloaded?
don don on August 25, 2006
I have avoided the foreach loop with
for ($x=0;$x7) {
// for example you can attach the file to a mail — don´t do this without security checks before
$mail->AddAttachment(${file_.$x},$_FILES['file_'.$x]['name']);
}
}
do not really know if this is faster as a foreachloop but it works for me
don don on August 25, 2006
sorry for the double post – but there was missing a line
I have avoided the foreach loop with
for ($x=0;$x7) {
// for example you can attach the file to a mail — don´t do this without security checks before
$mail->AddAttachment(${file_.$x},$_FILES['file_'.$x]['name']);
}
}
do not really know if this is faster as a foreachloop but it works for me
Jonhoo on August 25, 2006
But how about if the user presses the delete button 8 times.. Then your loop won’t catch all the files…
I’ve found a workaround using a while loop, but I really would prefer a for loop..
$found = 0;
$file = 0;
$max = setmaxlimithere;
while ($found lessthan $max)
$_FILES['file_'.$file] will always be one of the files the user uploaded
{
if (!empty($_FILES['file_'.$file]['tmp_name']))
{
//Do your thing here…
$found++;
}
$file++;
}
tommygeorge.com on August 26, 2006
Thanks to: Jose Rodriguez, above.
If you’re like me and still having trouble sorting through the files in PHP, here’s an example of doing so…
In this example I’m using htmlMimeMail, and adding attachments to an email.
You should be able to pick out the important parts, especially with all of the other information available here.
First, just use the script as-is. It will upload the files to the server just fine.
Then, in PHP…
reset ($_FILES); // Be sure that the Array Pointer starts at the beginning.
while ( list($key, $value) = each($_FILES) )
{
$tmp_name = $value["tmp_name"];
$name = $value["name"];
// As of now, the file is in the ‘/tmp’ directory.
// To place it on the server you would use something like
// move_uploaded_file($tmp_name, “folder/” . $name);
// But here I’m attaching it via a variable. (I know it seems wasteful, I just like it that way).
$attachment_file = addslashes(fread(fopen($tmp_name, “rb”), filesize($tmp_name)));
// Add the file to the attachment list (htmlMimeMail class)…
$mimemail->addAttachment($attachment_file, $name);
}//end while
I know this probably came out looking terrible here in the comment (no formatting), but I promise it works. =)
TommyGeorge.com
fara on August 31, 2006
Hello, nice code you have here =)
(and wow..look at those numerous comments! ^_^)
I tried to modified your code a bit,
I wanted to show preview of the images being uploaded,
I tried to create the image element in multifile_compressed.js…well, something like this:
var new_row_image = document.createElement( ‘img’ );
now I need to assign the img src…
new_row_image.src =
umm, the problem is… element.value is object, isn’t it?
document.write( element.value); will write the file path on the screen, but how could I assign that path to the img src?
Sorry if I rambled too much ^^
I hope someone out there will kindly lend me a hand?
Thanks =)
P.S.: Once again, thank you so much, Stickman!!
Malte on September 1, 2006
First off, thanks for your scripts, Stickman and Shawn!
Shawn, I think there may be a little bug in your php code. I should say that I am very new to PHP. Actually I programmed my first script two days ago. However, I have a pretty clear clue why it did not work.
What I noticed was that I was not getting any error message when the file upload was too large. Actually, count($GLOBALS['error']) was still 0 after I tried to upload a file that was too large, although it should have been 1; because of this code portion:
case (1|2):
// upload too large
$error[] = ‘file upload is too large for ‘.$file['name'];
break;
…and yes, $file['error'] (the switched variable). WAS 1, I checked that too.
I narrowed down the problem; I think it lies in the “case (1|2):” statement, more specifically the “(1|2)” part, which simply does not work for me. I programmed the following simple script:
The output is “D’oh!” on my server. So as you can see, my PHP does not seem to interpret it correctly.
When I changed the script like this:
The output was indeed “Looks like it’s working”.
As I said, I’m very new to PHP (but I do know C++). I never saw a statement like “case (1|2):” and it does not work for me. Maybe it’s only supported in some special versions of PHP or something like that… anyway, if anyone else is seeing this, the fix is obvious; replace “case (1|2):” by “case 1: case 2:” and “case (6|7):” by “case 6: case 7:”.
I’m running a Debian 3.1 “Sarge” server with Apache 1.3.33 and php4 module version 4.3.10-16.
Any comments?
Cheers,
Malte
Malte on September 1, 2006
Um, sorry, it seems that my PHP code was filtered out by the comments script, because of the <?php and ?> parts at the beginning and the end, I guess. So I’m trying again, this time without those tags
This is the script that outputs “D’oh!”:
$var = 1;
switch( $var) {
case (1|2):
echo “Looks like it’s working”;
break;
default:
echo “D’oh!”;
break;
}
And this is the script that outputs “Looks like it’s working”:
$var = 1;
switch( $var) {
case 1:
case 2:
echo “Looks like it’s working”;
break;
default:
echo “D’oh!”;
break;
}
Cheers,
Malte
Gregory on September 5, 2006
Hi, everyone!
Take a look at nice free Flash multiple files upload software tool http://www.element-it.com/MultiPowUpload.aspx
It also includes a lot of working examples of server-side upload scripts like PHP, ASP, PERL, ASP.NET.
spijky on September 13, 2006
check the smallville site on http://www.freewebs.com/smallville_benelux
priya on September 13, 2006
how to open multi file in open dialog box?
how to show all the selected file in control tool?
how to save it in database?
sibsoft on September 14, 2006
Hello,
thanks for great idea. We’ve used it in our upload progress bar. We also have 2nd method of adding files using “Add upload slot” button. Simpler than this method, but works well.
Thanks, anyway.
p.s. Great captcha. Entered 6 times
alex on September 14, 2006
10x for a great script
Tincho Liguori on September 20, 2006
Thanks for the Code. Is very usefull.
I have a concern that this code is not working into Internet Explorer 7.0 (i think that almost all the code (not only yours) does not work with Internet Explorer 7.0:) )
The problem that i have is that the button of the browse file is displaying as much times as the files that were added.
Also the linked files are displaying twice above instead of only one time.
Kabelo on September 22, 2006
How can somebody use this multiple file upload ,to upload files to the database,i have tried uploading to the database but in insert only one file .can you help.
russ on September 23, 2006
hi
James F. on September 26, 2006
Quick note – in IE7 and in Opera9, when I click “Choose..”/”Browse…”, it lets me pick the file, then it creates a second upload field and set of buttons, as well as displaying TWO of the selected uploads with their respective buttons once I click anywhere on the page again.
Then it continues to allow me unlimited uploads, creating a second field every time – so if I select five files, I have ten upload fields, all active, and ten displayed files with their buttons.
Any ideas? This is using
var multi_selector = new MultiSelector( document.getElementById( ‘files_list’ ), 3 );
multi_selector.addElement( document.getElementById( ‘fileBox’ ) );
James F. on September 26, 2006
Well it cut out my code, but it’s ASP FileUpload and Button – ideas?
Michele on September 26, 2006
What a brilliant idea!
but i need a control for upload only image file with max size 50 Kb
HELP ME!!!!!!
James F. on September 26, 2006
Quick update – using Bleeding Edge’s script, it no longer causes any problems in Opera9, but in IE 7, it still has multiple ASP:FileUploads appearing, though once an item is selected, it appears only once. Because it allows me to have an unlimited amount of uploads, I think it’s letting me create the new multi-selector many times.
Ideas?
Jim on September 30, 2006
Thank you very much for script! Was looking for something like this for a long time! THANKS!
volcan on September 30, 2006
it is a good thing
Walter on October 1, 2006
Nice piece of code, well done guy!.
Thanks.
Walter – Buenos Aires – Argentina
James on October 3, 2006
Quick question, how could I post a seperate field for text boxes? Say I want to do something like this:
/**
* Add a new row to the list of files
*/
this.addListRow = function( element ){
// Row div
var new_row = document.createElement( ‘div’ );
// Delete button
var new_row_button = document.createElement( ‘input’ );
new_row_button.type = ‘button’;
new_row_button.value = ‘ X ‘;
var new_row_comment = document.createElement( ‘input’ );
new_row_comment.type = ‘text’;
// References
new_row.element = element;
…
// Set row value
new_row.innerHTML = ‘‘ + element.value + ‘ ‘;
// Add button
new_row.appendChild( new_row_button );
// Add it to the list
this.list_target.appendChild( new_row );
// Set row value
…
new_row_text.innerHTML = ‘ ‘ + html;
new_row.appendChild(new_row_comment);
Is that right? Now how do I access that on the back end?
Andreas on October 5, 2006
It’s the “onchange” that wont work with konqueror. Easy fix is a button with the same action.
kiran on October 10, 2006
How do I get the list of files in the posted page. Using ASP.
Rajarshi on October 16, 2006
I need a way where the user will provide (type in) the path to a local folder, and submit the form, and all the files in that client machine’s folder has to be uploaded.
Any ideas?
Roger on October 27, 2006
The javascript works, but when I attempt to submit, how do I access the input elements server side, or is it all client side?
AJ on October 30, 2006
OMG you are a life saver man. Great Work!
I’m a newbie at this kind of stuff.
I need to know how the heck I can keep my server from timing out on the uplaod when the upload gets bigger because of it being multiple files.
Anybody got a suggestion?
Benny on November 10, 2006
hey Stickman, great bit of code!!!!
can i get your (or any one else’s) advice on how to get it working correctly? just using your code i set the Forms action to a php page. on this page i just want to go through the names of all the files and throw them onscreen.
but when i do an echo $_FILES[0]['name'] nothing is printed? your script says to leave out the name of the file input tag whcih i did and it still doesnt work?!!
can anyone please advise me as to what am i doing wrong?
many thanks in advance for any help
dave on November 14, 2006
hi!
i have the same problem as “Frank” “06/03/06 at 12:08 am.”
I cant get a handle to the tbody. I use:
If I check: document.getElementById(“files_list”), I get null. Anyone know why???
muthu on November 14, 2006
hi
i have a problem in uploading a file
i.e, whenever i entered some unknown characters like //,\\,oewioregreik……..
i have alerted the user about the unknown characters.
but after removing the unknown character, i uploaded a valid file with correct path
i am getting an error.
like this page cannot be displayed i.e, after i tampered the file in the browse button textbox i am getting the error. if i didnt tampered the file i am able to upload
can u please give sugession .
thank u
muthu on November 14, 2006
hi
can u please tell about how to remove the uploaded file dynamically in the browse button textbox if the user enters invalid characters. i am using asp.
Kevinin on November 15, 2006
This is the cooles thing!
syri on November 15, 2006
how ca i save the files after submit the form??!!
SF on November 17, 2006
In IE7 I can browse and select my images as expected. But when I submit the form only the first file is uploaded, regardless of how many images I actually selected. It works like a charm in Firefox. Has anyone seen or resolved this bug for IE7? Seems like a problem assigning array elements.
TIA!
Al on November 17, 2006
I am SSSOOOooooo new to this it isn’t even funny. But can you tell me where to put in the path that the files will upload to? thanks
Chris R. on November 24, 2006
I added a text input for file descriptions because I save my files in a SQl database, and also used those file descriptions to display in the div tags, instead of the file name.
Azhar on December 4, 2006
Hi
Sir, I cannot find the code to submit the query. Plz tell me where it is. How to submit the query and how it works to upload the file.
Waiting for ur reply.
Bye
pbd22 on December 7, 2006
hi.
is there anyway to grab the content length of the file being uploaded before the submit query
button is hit? i am trying to go post the bytes of the file along with the delete button and the
file name in the innerHTML.
i am guessing this wont be possible until the file reaches the server but i thought i would ask.
thanks.
zjyunhuan on December 8, 2006
pbd22 on December 9, 2006
hi.
how do you handle the hidden input fileds? my application requires that i dont limit the amout of uploads,
but allow the user to upload each file one-by-one in consecutive order. i am considering that a user may spend a good deal of time adding and deleting files. as a result, the below is likely to happen:
while this may be “hidden” it also creates a very large space above the first file path. the more add/deletes, the more space is created.
how do i gracefully handle the hidden input fields?
thanks again for a great script!
Simon Goellner on December 10, 2006
Man, this is awesome, you are amazing
Jason David on December 11, 2006
Thanks for the script man!!
midi on December 12, 2006
plzz …somebady help me…. how can i get size from that upload file
pbd22 on December 13, 2006
midi -
although i am myself having problems accessing the httpfilecollection on the server
(i am always getting a length of zero), i am pretty sure you cant get the size of the
file from the client. you have to do it on the server. try the ContentLength attribute
of HTTPPostedFile and send that information back via an xmlhttprequest object.
JFB on December 14, 2006
Hi All,
Someone made it work for coldfusion?
My front end it’s working, but not the back end. How can I pass the multiple file names on the submit?
Tks
JFB
hoshang on December 14, 2006
it this possible with file comments?
pbd22 on December 15, 2006
i am still having problems accessing my httpfilecollection on the back-end using vb.net.
i always get a length=0 for the collection. why is this happening? i would really apprecaite
it if somebody could help me with this here – or email me. i am using the below code:
Dim myfiles As System.Web.HttpFileCollection = System.Web.HttpContext.Current.Request.Files
Dim iFile As Integer
For iFile = 0 To myfiles.Count – 1
‘ get the posted file
Dim postedFile As System.Web.HttpPostedFile = myfiles(iFile)
Dim fileSize As Integer = postedFile.ContentLength
‘make sure it is not blank
If Not postedFile.FileName.Equals(“”) Then
‘Save File to the proper directory
‘postedFile.SaveAs(Request.MapPath(“folder/”) + System.IO.Path.GetFileName(postedFile.FileName))
End If
Next iFile
Scarface on December 15, 2006
Hi. I have a script that sends an email to a certain address. I would like to add the option of attaching multiple files. Is this script what I am looking for? If so, could someone help me incorporate it into the page I have?
Thanks
Vlad on December 15, 2006
Asp.net programmers! Plz, help.
How can I get files to upload in server side? If I use Request.Files collection – it’s always has 0 elements. What’s problem ?
Vlad on December 15, 2006
response to my previous question:
Form must has attribute enctype=”multipart/form-data”.
pbd22 on December 15, 2006
that doesnt seem to work for me tho. i am going through a hidden iframe and i am wondering if that is causing problems with reading the file colleciton on the server… would really apprecaite advice here… tnks.
Oscar Cala on December 16, 2006
hey, good code, very proffessional, it is true javascript, congratulations…
hoshang on December 17, 2006
Suddenly it doesn’t work anymore :S
Venakata Sarma on December 18, 2006
Hi
how to get this from server side. ok I am uploading some files..then how do I get them in the action class.I am using struts frame work.I want to upload any number of files.plz help me yar.. Its really urgent.
ashishnaik1 on December 23, 2006
Cool! Thankyou
Jcart on December 27, 2006
Just to let you know I’ve decided to implement this on one of my sites, although I did notice after some debugging considering the actual element used to input the files is left blank this creates an extra file element. For those of us that actually validate our content, this creates a small problem because we must take extra precaution to avoid this empty field or delete it. You should consider removing this input upon submission.
Thanks for the useful snipplet.
Greg K on December 27, 2006
Hi! Thanks for taking the time to provide this sweet and fast script. I am wondering if it is possible to have a check box or other form element load up beside the delete button in the list of chosen files and pass this info onto the upload script…
Having trouble wrapping my head around it… admittedly I’m a newbie!
Cheers,
Greg.
Ñâåòî÷êà Êîíôåòî÷êà on December 28, 2006
Òðåáóåòñÿ ïðîâåñòè êàíàëèçàöèþ â êîòåäæíîì ïîñåëêå.
Èùåì ÷òî-òî âðîäå [url=http://arsi.com.ru]âîò òàêèõ[/url] òîëüêî â Ìîñêâå.
EDH on December 31, 2006
Hi,
Is there another approach than the input type=file approach that forces users to browse to/through directories to select the file(s) they want to upload ?
I would like to do the following. Present a user with a list of files that are located in a particular directory on his pc. Then offer that user the ability to select one or more files from this list for upload.
Is this possible using plain javascript and html, or do I need (Java world) an applet ?
Any help would be appreciated.
Thanks,
EDH
Chris on January 1, 2007
Hmm! Where did my comment go I don’t see it anymore
Chris Mc on January 1, 2007
I shall try to re-iterate what I said. This is an awesome script by the way!! I have an image gallery program that I have created and have implemented this script into it. The problem that I am having is when a user uploads an image who’s file name has a single quote in it. when using the form POST method, and PHP I call this print $_FILES['file_0']['name'] to recall the name of the uploaded file; If I have a file named chris’s_pic.jpg when file gets uploaded it’s name gets truncated to s_pic.jpg. So my question is, is there any way to escape or use some sort of wrapper to protect file name integrity?
Thanks again for this wonderful script.
pbd22 on January 3, 2007
would really apprecaite an explaination of .NET server processing. tons of questions about this. I have tried Jesse H’s response above but i keep getting a httpfilecollection count of “0″. I am trying to pass the URL string through an IFrame. The below tag always fails:
if i remove the callToServer method, the server-side file count is correct once i post the form but i want the “fake ajax” feel of the hidden iframe.
please help. why can’t i get this to work with a hidden iframe?
John on January 5, 2007
Yeah, an example of asp server side file that handles the files to upload would be really great. I also get a Request.Files count of 0. Looks like some people have already figured out the solution. Can you please share?
Thanks
pbd22 on January 8, 2007
john -
i have been able to execute this code successfully without passing it via hidden iframe.
if you are getting a server-side count of zero, make sure that your form tag is correct.
are you using the enctype=multipart/form-data and submit=(your server file) attributes
in your form tag? also, if you are using asp.net with master pages, make sure that you
are not enlosing your form tags inside of master page form tags. that could (will) muck
things up.
my problem has to do with the processing of the iframe code. i would REALLY APPRECIATE
IT if somebody could show me SUCCESSFUL iframe javascript code for file upload. I have
been using the code provided on the Apple Computer site, and it keeps failing but i havent
been able to figure out the problem (i am losing hair here). here is the link:
http://developer.apple.com/internet/webcontent/iframe.html
if somebody out there has been able to use stickman’s file upload code with iframes, would
you mind sharing? please?
thanks.
peter (pbd22)
Ivik on January 9, 2007
Nice program, but I had a really hard time to make it work correctly, it always just sent the first file I added and not the other files. Then I found out that the problem was that I had inserted a text field in the same form as the file input was located.
How can this be fixed, how can I be able to have more fields in the same form and still use this nice script?
riko on January 12, 2007
how can i combine it with php, i never working with js before.
Rajesh on January 23, 2007
Multiple file upload using struts
I have tried this ,and I got result.
****************In jsp*********************
Photo 1
Photo 2
*************** in struts-config.xml*************
***************in FileUploadForm.java***************
public class FileUploadForm extends ActionForm {
private List formFiles = new ArrayList();
public List getUploads() { return this.formFiles; }
public void setUploads(int iIndex, FormFile formFile){
this.formFiles.add(formFile);
}
}
***************In execute method of FileUploadAction.java***************
FileUploadForm uploadForm=(FileUploadForm)form;
List myFiles =(List) uploadForm.getUploads();
for(int i=0;i
wekkaw on January 26, 2007
Hi there thanks so much for a this great script.
I’ve modified it a bit to restrict the type of files selected. Just in case anyone wants to do the same thing, here is the change:
if( element.tagName == ‘INPUT’ && element.type == ‘file’ ){
// Element name — what number am I?
element.name = ‘file_’ + this.id++;
// Add reference to this object
element.multi_selector = this;
// What to do when a file is selected
element.onchange = function(){
var validFileType = checkFileType(element);
if(validFileType){
// New file input
var new_element = document.createElement( ‘input’ );
new_element.type = ‘file’;
// Add new element
this.parentNode.insertBefore( new_element, this );
// Apply ‘update’ to element
this.multi_selector.addElement( new_element );
// Update list
this.multi_selector.addListRow( this );
// Hide this: we can’t use display:none because Safari doesn’t like it
this.style.position = ‘absolute’;
this.style.left = ‘-1000px’;
}
};
Here is the Function
function checkFileType(inputField)
{
var allowd = /\.png|\.jpg|\.gif/i;
var filename = inputField.value;
if (filename.search(allowed) == -1)
{
alert(“The type of file you selected is not supported.”);
inputField.form.reset();
return false;
}
return true;
}
Simple use of this script (works on Firefox) on January 29, 2007
Change in the first line of form:
action=”post.php” method = “post”
then create post.php code:
“;
}
else
{
echo “Possible file upload attack!”;
}
echo ‘Here is some more debugging info: ‘;
print_r($file);
}
?>
pbd22 on January 29, 2007
hi,
have been working on fixing some errors in my upload code using this script.
i am noticing that, when i use this script *and* send the files via a hidden
iframe the httpfilecollection count is zero. after further inspection, i am finding
that the server page isn’t recognizing the multipart/form-data enctype on page_load.
but, i have that attribute clearly defined in my form tag on the client page. so,
i am wondering if anybody has had a similar problem? i would really apprecaite
suggestions. thanks.
Nil on February 2, 2007
can any body tell me how can i implement this code with struts .and how i will get i mean differentiate three different files.because they are coming with same id.
Nate on February 6, 2007
Can you display only the filename and not the path? If so, please show me what line to edit in the code to do that.
Nate on February 6, 2007
I’d love to see the code to add captions next to each image.
Nate on February 6, 2007
The following was posted above, but this does not work when tested it in Firefox 2
I have made a little mod in order to display only the filename i/o full path+filename :
element_work = element.value;
element_tab = element_work.split(â€\\â€);
nbr_elements = element_tab.length;
new_row.innerHTML = element_tab[nbr_elements-1];
instead of :
new_row.innerHTML = element.value;
cheers
Again, I’d love to see some code to only show the filename and not the full path.
Nate on February 8, 2007
I’d really love to see the code to add a caption / description next to the filename of each uploaded file. Can someone please post some code to do that?
Corey on February 11, 2007
This multiple file uploader is awesome!
I’m using Shawn Parkers script to upload the files
http://www.top-frog.com/files/scripts/upload_sample.phps
The thing that confuses me is that I am trying to make it image only not movies pdf’s etc… I commented out the part with all of the other extensions but it is still allowing the file to upload. I’m pretty much a noob at more advanced programing so any suggestions will be welcome!
phreaki on February 12, 2007
great script, took care of what I needed, works great.
RamaKrishna on February 12, 2007
Dear sir,
I’ve a small doubt regarding the script file. Is it possible to add a text box with each file at choosing the file and can process those text boxes like as file in the normal scenario.
waiting for your reply,
thanks & regards,
RamaKrishna.P
Nibinaear on February 12, 2007
Great tutorial. I am now going to use this on our awards website to let users upload multiple files as supporting evidence in their submissions. Cheers.
Ramakrishna on February 13, 2007
sir,
thanks for developing such a wonderful script file and is very useful for many needs in multiple file uploads, but i’ve a small problem regarding the text file apart from the files i.e i need to attach a note to every file i choose and that note should be inserted into database but i;m unable to locate the text type along with files while uploading. Please help me in this area as is very important for me.
Ramakrishna.P
Software Engineer,
Karishma Software Ltd,
Secunderabad.
India.
JarsofClay on February 13, 2007
Hi people,
i wanted to add move up and move down functionalities to the list. I should be able to select the files and sort them. Can anyone please help me on this…
Thanks in advance
TC on February 19, 2007
There are 300 some comments saying what a great script this is. Here’s one more. Thanks!
Nibinaear on February 19, 2007
This code tends to add an extra empty file element for every file you upload. For example, if I try and upload one file I will get back file_0 and file_1, file_1 being empty. I have to use the unset function WHEN using PHP to destroy these empty array positions. Adding 3 files where the maximum is 3 produces 3 files as expected.
Also, using Opera means that uploading multiple files means you only get the first one back in some instances. I tried the example and it worked with Opera (9.10) but when placed in quite a large template it didn’t work and I only got 1 file back.
Thirdly, it might be a good idea to tell everyone to add a MAX_FILE_SIZE HTML attribute to all forms when files are uploaded. If you don’t you can get back partially uploaded files back when checking using $_FILES['file_0']['error'] in PHP.
fanfan on February 25, 2007
Very very useful!
Many thx!!
–
F
handyflatrates on February 25, 2007
This is a really useful script and i searched for such a long time. But i would really appreciate, if you would show how to go on with the data. I tried to use the PHP-File from the comment you posted but it’s generatin gerrors.
Thanks for your JS!
lifeguru on February 27, 2007
Thank you. This script made my life soo much easier
Rene on February 28, 2007
Nate: The code posted earlier DOES work in FireFox when you change the quotes to normal quotes
so †to “.
The following code only shows the filename:
element_work = element.value;
element_tab = element_work.split(“\\”);
nbr_elements = element_tab.length;
new_row.innerHTML = element_tab[nbr_elements-1];
instead of :
new_row.innerHTML = element.value;
I do also have a question, asked many times before above but unanswered:
Why does it only send the first selected file in FireFox (2.0)?
print_r($_POST); alwyas shows only 1 file!
I.E works fine, but i can’t use it if it does not work in Firefox. Anyone same problem / solutions?
Winnie on February 28, 2007
I’d like to upload multiple files as a Zip like ZipDeploy does. Is it possible?
Arawee on March 3, 2007
WaaaaW!
thanx a lot (Stickman and also Luis Torrefranca) and all,
:”)
Nayana on March 5, 2007
hi,
this helps a lot…. nice code..
Bonn Party on March 6, 2007
Thanks a lot, i searched for it a long time, since i saw it on http://www.sevenload.com . We’ll propably use it, too in the next weeks. Really useful, thx!
Pomp on March 7, 2007
We are trying the above code.
Once the files are added we could find the added files using Request.Files at the server.
Can any one help with this.
Rob Daniel on March 13, 2007
Your code has greatly advanced the file uploader that I had on my site. I credited StickBlog for making the code and I put a link back to this very page. Thanks again and I will look to yall for any future coding help I need.
Rob
Mark on March 14, 2007
Hi, nice site!
Suresh on March 30, 2007
i want to know how to nicer the tag without using tag
Sureshkumar N on March 30, 2007
Thanks for the scirpt it worth a lot!!!!. please notify me if any thing interesting is going on
yan on April 3, 2007
how i can do for multi list in one form ?
Diego on April 12, 2007
I released a similar plugin for jQuery a few days ago and it may be of interest to people reading this page.
http://www.fyneworks.com/jquery/multiple-file-upload/
Johan Schmidt on April 16, 2007
I was hoping to find some info about ZipDeploy
Matt on April 18, 2007
Wow. This is great but i suppose you don’t need me to tell you that. I am working on a project that needs to use photosharing and this is perfect! Saved me a lot of work
Thanks.
Nick Kilian on April 19, 2007
This script worked fine ‘as is’ in IE7, but would only upload 1 file in FF1.5 and OP9.2.
Chris Coleman at CXCV posted the fix, but there was a slight mistake. This is the correct code to get the input appended correctly to the form.
Change :
// Hide this: we can’t use display:none because Safari doesn’t like it
this.style.position = ‘absolute’;
this.style.left = ‘-1000px’;
To :
// Append the input to the form for use in FF1.5 and OP9.2
document.getElementById(‘upload’).appendChild(this);
// Hide this: we can’t use display:none because Safari doesn’t like it
this.style.position = ‘absolute’;
this.style.left = ‘-1000px’;
You also need to add an id=”upload” to the original form variable.
Nick Kilian on April 19, 2007
Steve Owen in CIX posts a nice layout change for the div element. There’s just one mistake, a missing – in the count decrementer. Below is the new code with the added – at the end.
// Decrement counter
this.parentNode.element.multi_selector.count–;
Regarding my post above, it seems copy/pasting from these comments affects single quotation marks, so I’ve had to find/replace them all to get the code working correctly.
Pablo on April 23, 2007
So, how to fix the script for Safari??
Please, anybody can paste full script here.
Joe Parsons on April 25, 2007
Anybody have any luck using this on an iBook under Firefox. I keep getting:
Please enter a valid path on your local computer system.
Works fine under Windows, (IE, Netscape, Firefox, etc.)
me on April 26, 2007
must just say brilliant script, bt can we use any upload script or must there be sumthign specila bout it cos mine only uploads the last file out of the selscetion
myself on April 26, 2007
must just say brilliant script, bt can we use any upload script or must there be sumthign specila bout it cos mine only uploads the last file out of the selection
ahussam on May 21, 2007
hi all, great code thanks,
I edited the code a bit to be able to align the delete button to the right, but now I have a problem when deleting i get a javascript error.
here is my edited code part:
this.addListRow = function( element ){
// Container Row div
var out_row = document.createElement( ‘div’ );
out_row.style.width = ‘100%’;
out_row.style.background = ‘#EEEEEE’;
out_row.style.position = ‘relative’;
// Text Row div
var new_row = document.createElement( ‘div’ );
new_row.style.width = ‘600px’;
new_row.style.position = ‘relative’;
new_row.style.top = ‘3px’;
new_row.style.styleFloat = ‘left’;
new_row.style.cssFloat = ‘left’;
// Delete button
var new_row_button = document.createElement( ‘input’ );
new_row_button.style.styleFloat = ‘right’;
new_row_button.style.cssFloat = ‘right’;
new_row_button.type = ‘button’;
new_row_button.value = ‘Delete’;
new_row_button.style.position = ‘relative’;
// References
new_row.element = element;
// Delete function
new_row_button.onclick= function(){
//node.parentNode.removeChild(node);
// Remove element from form
this.parentNode.element.parentNode.removeChild( this.parentNode.element );
// Remove this row from the list
this.parentNode.parentNode.removeChild( this.parentNode );
// Decrement counter
this.parentNode.element.multi_selector.count–;
// Re-enable input element (if it’s disabled)
this.parentNode.element.multi_selector.current_element.disabled = false;
// Appease Safari
// without it Safari wants to reload the browser window
// which nixes your already queued uploads
return false;
};
// Set row value
new_row.innerHTML = element.value;
// Add button
out_row.appendChild( new_row_button );
// Add text
out_row.appendChild( new_row );
// Add it to the list
this.list_target.appendChild( out_row );
javascript error is “this.parentNode.element.parentNode is null or not an object” on IE7, any idea how to fix this ?
Mike S on May 22, 2007
Though this code seems to work fine when used w/ the example .html file, if i use within my own email form, var_dump($_FILES) always returns just one file.
I have seen this mentioned in previous comments above. Has anyone figured out what this issue is?
Thanks in advance for any help.
stevie on May 28, 2007
Good post
dj on May 30, 2007
im planning to use this control snippet in the project that im currently working on.. So ive converted this from html to aspx, however there seemed to have an error on this line “this.parentNode.parentNode.element.multi_selector.count–;”.. can someone please help me.. i could provide a link to my complete source code
I’m using the script in a rails application:
changed in multifile.js:
element.name = ‘file_’ + this.id++;
to:
element.name = ‘album[picture' + this.id++ + ']‘;
In rails I’m using this snippet in the controller:
params[:album].each{|key,asset|
@asset=@album.assets.create
@asset.uploaded_data=key
@asset.save
}
Does anyone have a more elegant solution for the rails part?
Cyril on June 5, 2007
It seems it does not work when the form is in a pop-up and the div in the parent window.
Ganesh on June 7, 2007
Hello all,
what about displaying actual images instead of the path of the images and delete button?
Thnaks,
it2051229 on June 9, 2007
well yeah thanks for the script.. but uhhmm i wanted to style my button.. how can i style my button with CSS if the “id” and “class” property is occupied??
Chris on July 6, 2007
Please tell me how you styled your “Browse” button above! I have looked at all the overlaying options, but they suck. I need a CSS solution!
Mahes on July 10, 2007
how do i actually pass the value over to my asp page?
sidnei dasilva on July 16, 2007
Thanks so much for sharing the script
Great work! Congratulations!
-Sidnei
stoney on August 4, 2007
how can we up load a file without browsing it?. ie, we know the path of the file and we want to upload it without clicking on the browse button…
Max on August 4, 2007
Great work, I must thank you, even if there are so many comments, that means the same as mine
..sorry for my english
Chris on August 13, 2007
Please don’t use for loops to pick up the files…
Here’s a better example:
foreach($_FILES as $file) {
if($file['error']==0) {// keeps blank files out
//your upload code here
} // end if statement
} // end foreach
chris on August 14, 2007
Here’s my edited file
Changes include:
File name is not absolute path (so ‘file.doc’ instead of ‘/home/foo/Desktop/file.doc’) credit Steve Owen
Remove button is to the left of the file – credit Steve Owen
‘Remove’ is now a link instead of a button
function MultiSelector( list_target, max ){
this.list_target = list_target;
this.count = 0;
this.id = 0;
if( max ){
this.max = max;
} else {
this.max = -1;
};
this.addElement = function( element ){
if( element.tagName == ‘INPUT’ && element.type == ‘file’ ){
element.name = ‘file_’ + this.id++;
element.multi_selector = this;
element.onchange = function(){
var new_element = document.createElement( ‘input’ );
new_element.type = ‘file’;
this.parentNode.insertBefore( new_element, this );
this.multi_selector.addElement( new_element );
this.multi_selector.addListRow( this );
this.style.position = ‘absolute’;
this.style.left = ‘-1000px’;
};
if( this.max != -1 && this.count >= this.max ){
element.disabled = true;
};
this.count++;
this.current_element = element;
} else {
alert( ‘Error: not a file input element’ );
};
};
this.addListRow = function( element ){
var new_row = document.createElement( ‘div’ );
new_row.innerHTML = ‘[';
var new_row_button = document.createElement( 'a' );
new_row_button.setAttribute("href", "#");
new_row_button.appendChild(document.createTextNode("remove"));
new_row.element = element;
new_row_button.onclick= function(){
this.parentNode.element.parentNode.removeChild( this.parentNode.element );
this.parentNode.parentNode.removeChild( this.parentNode );
this.parentNode.element.multi_selector.count--;
this.parentNode.element.multi_selector.current_element.disabled = false;
return false;
};
var c = element.value.lastIndexOf('\/');
if (c != -1)
html = element.value.substring(c+1);
else {
var c = element.value.lastIndexOf('\\');
if (c != -1)
html = element.value.substring(c+1);
else
html = element.value;
}
new_row.appendChild( new_row_button );
var new_row_text = document.createElement( 'span' );
new_row.appendChild(new_row_text);
new_row_text.innerHTML = '] ‘ + html;
this.list_target.appendChild( new_row );
};
};
and the php file it posts to:
if($_FILES) {
foreach($_FILES as $file) {
if($file['error']==0 ) {
$uploadDir = ‘upload/’;
$uploadFile = $uploadDir . $file['name'];
move_uploaded_file($file['tmp_name'], $uploadFile);
} //error is 0
} // foreach
} // if files
I do error checking and more processing of the uploaded files, but they were very specific to my function so I left them out to be as generic as possible. Hope it helps.
???? on August 29, 2007
???????????
Balendu Sharma Dadhich on September 7, 2007
Very innovative way to upload multiple files, which is otherwise a very tedious task.
Sathish on September 19, 2007
Nice work friends.
Code is working superbly..
But i need to upload only image files.
Is there any script to validate before uploading.
If so please send me the code across chumsat@gmail.com
Thanks in advance
zn0ppy on September 20, 2007
very nice script. found the trick behind this multifile uploads i was search for days
Dave on September 21, 2007
This is really beautiful. I’m definitely looking for this solution and one other component. Do you know if it is possible to filter out the files shown by say file extension or filenames? If I could do that, this would really work well for me as I have an instance where I have to allow the user to select about 100 files and it would help avoid mistakes if I showed only the file file1_1.jpg, file1_2.jpg… so that they put the right file into the right slot when the files are properly named (they won’t always be, so I also need to allow them to turn the filter off).
THanks,
dave
Blake on September 24, 2007
I have gone through every comment on this thread (not necessarily perfectly, mind you) and added in all the fixes that seem pertinent, but I still cannot get this script to successfully send the file data to the server in Firefox 2.0.0.7. It works just fine in MSIE, but Firefox (on the php backend) sees empty file data. Is it just me? Any ideas??
Terrence Brannon on September 24, 2007
Hi, it seems that two file parameters are passed when only one file is uploaded.
good job.
Dejan on September 25, 2007
I saw some people asking this in this in here but I’m not shure if somebody posted this before me.
It’s about styling the Browse button and the text box next to it so we get a nice looking Browse button with or without the nice looking text box.
I joined this fantastic solution with another great one from Michael McGrady to achieve formating of the Browse button and the text box. To one of our clients the text box looked kinda disfunctional to end-users, since the selected files are constantly disappearing and I quite understand them in some way (nobody uses command-line style inputs theese days).
So anyone interested in a nice looking Browse button with no text box, just contact me(djefim@gmail.com)! I would post it here but it’s still looking nasty and I’m way behind schedule
Jenny on September 27, 2007
I’m no guru in Ajax/DHTML so I wasted a couple hours trying to find the AJAX in that neat solution.
Stickman on September 27, 2007
Jenny: I don’t know where you got the idea that this has anything to do with Ajax — certainly not from the article, or anything in the code.
What exactly were you looking for?
babacan on October 14, 2007
Thanks. very good article
Greg Mallon on October 15, 2007
Stickman,
Before I forget. Thanks. This looks to be an elegant, clean and simple approach to handling this problem. I appreciate the time you’ve taken to do this. I come from a Java background mostly and have done this before by allowing user to upload multiple docs, one at a time, with meta-data associated with each. New to .NET and just needed a simple, clean implementation since time is short. Thanks again.
Greg
Abhijit k Jadhav on October 16, 2007
hi Great job
I want some modification in code.
I want to have a space of near about 60px or more between filepath and delete button.
Please help.
Thanks
bye
Tom Webdesign on October 17, 2007
nice post but i’m looking for a file uploader where I can select multiple files at once.
When you need to upload 100 files you have to select them one by one.
Suhaib Malik on October 18, 2007
thanks a million for this wounderfull script. keep rocking
Silpa on October 22, 2007
can you please provide me the code to open the attached file.with the same code as above i need to have this feature also to oprn the file.
Thanks in advance
ctraos on October 24, 2007
muchas gracias, muy buen post
D
Eric Mitchell on November 3, 2007
Doubt anyone will make it down this far but…
Wouldn’t it make the Delete button’s “onclick” event handler a little less wordy if the file input element was added to the button itself, rather than the row?
For example:
new_row_button.element = element;
instead of:
new_row.element = element;
allows:
this.element.parentNode.removeChild( this.parentNode.element );
and:
this.element.multi_selector.current_element.disabled = false;
instead of:
this.parentNode.element.parentNode.removeChild( this.parentNode.element );
and:
this.parentNode.element.multi_selector.current_element.disabled = false;
I hate having to keep track of the document hierarchy as I’m reading code. This is a little more straightforward.
Thanks for the solution! And your code formatting is great, BTW (i.e. similar to mine).
P.S. I see I have to give my e-mail address (good for 30 days). Having read your interviewing comments about putting a web site on your resume I’ll ask, should you end up on mine, to keep in mind that it’s aimed at 85-year-old users who use WebTV – even frames are too exotic.
Juan on November 9, 2007
excelente !!! facil de integrar !
surya on November 10, 2007
i want to check at the time of uploading the input fiie is opened or not
Nguyen Duc Manh on November 12, 2007
why you don’t upload your php file ???
I had a problem when form didn’t sent the top number of files, the FILES array had an extra empty field. I tried to resolve it deleting the empty input type file at submit.
I added this funtion to the script:
…[CODE]
this.CheckEmpty = function ()
{
//alert (“TAG: “+this.current_element.tagName+”TIPO: “+this.current_element.type+”VALOR: “+this.current_element.value+”LONG: “+this.current_element.value.length);
if(this.current_element.value.length==0)
{
if (this.current_element.parentNode.removeChild(this.current_element)) return true;
}
};
[/CODE] …
just before the last };
Then is needed to add an eventhandler to the FORM tag: onsubmit=”multi_selector.CheckEmpty();”
in this way:
And thanks for this script.
Sean on November 28, 2007
Hi, Can anyone help me. I’m using the multifile.js version without any changes and it’s not working on Firefox. Not sure what’s causing that. Also I everytime I add a file I also capture the contents of a textbox. However, I only want to add the file if the textbox is not blank. How do I do this?
hobrob on November 29, 2007
It’s not asynchronous, and there’s no XML. THIS IS NOT AJAX. Unless you put the contents of a file into a get / post variable of an XMLHttpRequest and send it to a script that creates a file on the server with the contents of your variable, there is no such thing as an AJAX file transfer. Why do people find it so hard to distinguish between Ajax and standard Javascript DOM manipulation?
Stickman says: I’ve said it before several times but apparently I need to say it again: I know it’s not Ajax, and I never claimed that it was. Read the article again and see if you can see any mention of Ajax…well? Nope, that’s because it’s not there. And it never was.
In fact, I think I’m going to edit the article right now to point this out more clearly, to avoid any more such high-handed comments.
SUDHI GANGAL on November 30, 2007
Thanks the code u have given for browse.
THROUGH CODE FILES ARE STORED IN .SO NW I HAVE I QUESTION THAT AS IT CONTAIN IN DIV HOW TO ACESS THE FILES AND UPLOAD TO THE SERVER .
BECAUSE DURING THE UPLOAD IT ONLY KNOWS THE TAG NOT THE DIV
PLEASE HELP ME .IF ANYONE TRIED.
Craig on January 9, 2008
Easiest way to strp the filename:
Replace:
new_row.innerHTML = element.value;
with:
var m = element.value.match(/(.*)[\/\\]([^\/\\]+\.\w+)$/);
new_row.innerHTML = m[2];
Cheers, Craig
soulz on January 21, 2008
Alright I’m a bit new with the CSS concept and XHTML.. understand java enough to get by.. and am fairly good with php and ajax.. So, I found this script the concept is fantastic.. love it very much so.. but for once I am stumped on coding… maybe its cause i am beyond sleep or just burnt out from other projects I dunno.. but I guess my questions would be to this..
I want to change the look to like what you have well.. similar but more conforming to the look of the site I am using it on. grant it its a backend script on the site that i plan to use it for an noone will see it but me and I could leave it the way it is, but I am to say the least anal about looks.. so that said.. how can I change the div layout from plain to pretty? just a simple sample will sufice ill figure out the rest from there hopefully..
and one other thing. how would i integrate this in with Shawns upload script?
email is soulzllc@gmail.com to any that can help..
Mister B on January 25, 2008
Awesome work – works really well – thankyou very much! I had to extend it so that i could add a description text box for each file to upload. It was reasonably simple to do. What I should have done though (NB for next time, or for anyone that needs to do the same), is create a generic container object to hold the input file and the input text control in, and then that could be manipulated in the same way that you are currently manipulating just the file input control. If this is done, then you would be able to group all sorts of different html controls with a single file upload with the same code base. oh well… for next time!
Shaun on February 1, 2008
can someone email me the updated script with the RESET code
Kristy on February 5, 2008
Love the script. Easy, Neat & User Friendly… my thanks to Jpep for his tip on getting started with the upload script:
$file_count = sizeof($_FILES);
for ($i=0;$i
Roland Hentschel on February 6, 2008
Great Script,
yet I’m confused about what kind of script I should write
for the “your_script_here.script” …
Would be really kind of you to help me out ?!?
( -: roland :- )
Kyle on February 13, 2008
I’m trying to allow for a description/caption to be added for each doc…if anyone can help me out, point me in the right direction or share their hack…it would be appreciated
ChrisLang on February 16, 2008
Hi Stickman and Hisham Al-Beik,
regarding the delete all. i cannot find any file here on how to delete all. but here is the code:
example.html
var TabPlane = document.getElementById(‘files_list’);
var newPlane = TabPlane.cloneNode(false); // no child nodes;
TabPlane.parentNode.replaceChild(newPlane,TabPlane);
But i tried so many times and ways to removeChild (insertbefore), would you please help.
Thanks
smeerkahoven on February 22, 2008
hi… im trying to upload files using php.. but i wanna kwno if there are a way to upload them without html tag…just using an url: /home/me/file.txt ….in a hidden tag or something…but validating with POST or GET to get the file url to upload…plz …
Justin Cunningham on February 25, 2008
I made a flexible flash multiple file upload applet. It’s called Multi Bit Shift, and is licensed under the LGPL. It has real time upload status monitoring and queuing, and is extensively documented both internally and externally. In addition, screencasts are available and any of the text or color schemes can be customized. I hope it can be of some help, check it out at http://mutlibitshift.com.
JC
Randy on February 25, 2008
Thanks for the great code!
palwinder on February 28, 2008
Thanx for,
Really, it was very helpful for me, i just got it that i wanted.
Thankx once again dear.
LinuxDeveloper6666 on March 6, 2008
Thanks for the nice script. It took me two days to get this working.
However my boss has a requirement. Does any one know some upload script like the following?
http://ajaxuploader.com/Demo/multiple-files-upload.aspx
The above script is built in .NET. I think it’s possible to achieve the same result using PHP.
Thanks
mayaka on March 6, 2008
Hi
thks for this script, but i still have a problem with
when i try to print the content of $_FILES
print_r ($_FILES);
i have an empty entry in the table (i try to upload just 2 file )
please help me
FILES:Array
(
[file_2] => Array
(
[name] =>
[type] =>
[tmp_name] =>
[error] => 4
[size] => 0
)
[file_1] => Array
(
[name] => ovh-logo-gauche.gif
[type] => image/gif
[tmp_name] => w:/var/tmp\php39C.tmp
[error] => 0
[size] => 1854
)
[file_0] => Array
(
[name] => webaffaires.jpg
[type] => image/jpeg
[tmp_name] => w:/var/tmp\php39D.tmp
[error] => 0
[size] => 11575
)
)
Shelon Padmore on March 8, 2008
Is there a way for this control to select a folder also???
- Shelon Padmore
Stickman Games on March 12, 2008
Crazy coding
Kyle on March 13, 2008
I’m trying to allow for a description/caption to be added for each doc…if anyone can help me out, point me in the right direction or share their hack…it would be appreciated
Philip on March 14, 2008
@mayaka:
It looks like you have not changed the max parameter from the default of three to your desired number of uploads. When calling the MultiSelector() function, specify 2 as the second parameter.
I could be wrong, however.
@Stickman – Thank you very much for this… It is much more elegant than the solution that I was using, which was to use AJAX (ugh) to create additional file input elements or using the fileReference class in flash (double ugh) to create upload forms.
Sanket Sirotiya on April 1, 2008
Thanks Dude!!!
Misha on April 1, 2008
Thank you a lot for the script.
I am going to use it with php to upload files and to put them to MySQL DB.
<?
for ($i = 0; $i < 3; $i++)
{
print $_FILES['file_'.$i]['name'].”;
}
?>
pervaiz akhtar on April 2, 2008
good work
but i feel problem when i used javascript in content page. what is solution of it
Luiz Lopes on April 4, 2008
This is great, a really awesome script. It definitely makes things a lot easier to work with. Good Job!
ram on April 4, 2008
Nice work.. Just wanted to know if any one is aware of mulitple selection of files while uploading.
dylan on April 9, 2008
For those of you who are still trying to CSS-ify the delete button (and other elements).. I set the “id” tag with,
new_row_button.setAttribute( ‘id’, ‘multifile-butn’ );
I think you can set the “class” tag similarly, though I haven’t tried.
Rhaka on April 15, 2008
Man i’m still float with
element.name = ‘userfile[]‘;
b’cos in my PHP
$file = $_FILES['userfile'];
$k = count($file['name']);
for($i=0 ; $i < $k ; $i++)
{
if(isset($save_path_thumb) && $save_path_thumb!=”")
{
$name = split(‘/’,$file['name'][$i]);
move_uploaded_file($file['tmp_name'][$i], $save_path_thumb.$name[count($name)-1]);
}
}
it’s still can’t work…i can upload several even only for 1 image.please reply imediately..thanks
Rhaka on April 15, 2008
it’s still can’t work…i can’t upload several even only for 1 image.please reply imediately..thanks
jake on April 26, 2008
Ok i need a tiny bit of help, i need the element name and id to be the same because of how my form script works. How do i do this? I can get the id to come up but the numbering does not stay the same with the id and name.
please help
Cromatino on May 4, 2008
Hi. Thanks for the script, that’s what I need for a my simple struts project…but…I have a question: in the action you put ‘action=”your_script_here.script”‘. Can I pass the files to a Struts Action? If yes, how can I read the files? I’m trying to read them like File (and like FormFile too) but it doesn’t work. Which type I have to use to get this files?
Thanks, Bye.
woss on May 5, 2008
can anyone explain me is it possible to select multiple files at once and then upload them with the resto of the form??
Niz on May 6, 2008
Hi Stickman et al
Very, very helpful script.
Is it easy to add a piece of code that shows a progress bar for uploads? If so can someone point me in the right direction?
Regds
Niz
drvajra on May 7, 2008
ear Mr. Stickman and friends:
Greetings.
I am a teacher, and planning to set up a website for my students.
In my website,I would like:
1) Each student to be able to upload 15 to 20 files, at one time.
2. I will assign a Student# and password. This should be ‘required’ for uploading, to prevent unauthorized uploading.
2. Restrict upload File Types (for example *.exe).
3. I would like the files uploaded by each student to be stored on my website separately for each student.
4. I would like to be able to download from my website to my computer, my student uploaded files, for editing.
4. The ability to delete used files from server.
5. Ability to disable student#, so the same person cannot upload without new approval.
I will greatly appreciate if you could help me with implementing this in my website. I am familiar with HTML.
Thank you so much!
Dr. Vajra Sharma
PHP Developer on May 20, 2008
Hi, I am trying to upload multiple files in my server ( Web Host, not local).. But I want to test them before upload and also I want to show a progress bar about this upload..
How to do it?
Matt on June 13, 2008
This script is amazing.
If I already know the path of the files to upload, can these be listed in the before someone browses for a file?
Can I use php to do this?
Peter on June 25, 2008
Here’s a version I have modified to use the Prototype JS API and take an additional “options” parameter for increased versatility. Here is example usage followed by the code:
// Create an instance of the multiSelector class, pass it the output target and the max number of files and any desired custom options
var multi_selector = new MultiSelector( $( ‘files_list’ ), 50,{
name_prefix: ‘filename’,
use_array: true // name the elements with “[]” so PHP picks up the files as an array
});
// Pass in the file element
multi_selector.addElement( $( ‘my_file_element’ ) );
The modified code:
/**
* Convert a single file-input element into a ‘multiple’ input list
*
* Usage:
*
* 1. Create a file input element (no name)
* eg.
*
* 2. Create a DIV for the output to be written to
* eg.
*
* 3. Instantiate a MultiSelector object, passing in the DIV and an (optional) maximum number of files
* eg. var multi_selector = new MultiSelector( document.getElementById( ‘files_list’ ), 3 );
*
* 4. Add the first element
* eg. multi_selector.addElement( document.getElementById( ‘first_file_element’ ) );
*
* 5. That’s it.
*
* You might (will) want to play around with the addListRow() method to make the output prettier.
*
* You might also want to change the line
* element.name = ‘file_’ + this.count;
* …to a naming convention that makes more sense to you.
*
* Licence:
* Use this however/wherever you like, just don’t blame me if it breaks anything.
*
* Credit:
* If you’re nice, you’ll leave this bit:
*
* Class by Stickman — http://www.the-stickman.com
* with thanks to:
* [for Safari fixes]
* Luis Torrefranca — http://www.law.pitt.edu
* and
* Shawn Parker & John Pennypacker — http://www.fuzzycoconut.com
* [for duplicate name bug]
* ‘neal’
*/
function MultiSelector( list_target, max, options ){
if (options === undefined) {
// make an empty object so we don’t get errors checking properties
var options = {}
}
// Where to write the list
this.list_target = list_target;
// How many elements?
this.count = 0;
// How many elements?
this.id = 0;
// Is there a maximum?
if( max ){
this.max = max;
} else {
this.max = -1;
};
// What to prefix the upload field names with
if (options.name_prefix === undefined) {
this.name_prefix = ‘file_’;
}
else {
this.name_prefix = options.name_prefix;
}
// Whether or not the fields should be submitted as an array for the processing script. If set to true “[]” will be appended to the field name, otherwise it will be appended with a number
if (options.use_array === undefined) {
this.use_array = false;
}
else {
this.use_array = options.use_array;
}
// What CSS style to use for hiding the form elements
if (options.hidden_style === undefined) {
this.hidden_style = {
‘position’: ‘absolute’,
‘left’: ‘-1000px’
}
}
else {
this.hidden_style = options.hidden_style;
}
// A CSS classname to use for hiding the form elements. This will take precedence over the style to ensure the default style is not used when a classname is provided.
if (options.hidden_classname === undefined) {
this.hidden_classname = null;
}
else {
this.hidden_classname = options.hidden_classname;
}
/**
* Add a new file input element
*/
this.addElement = function( element ){
// Make sure it’s a file input element
if( element.tagName == ‘INPUT’ && element.type == ‘file’ ){
// Element name
if (this.use_array === true) {
element.name = this.name_prefix + ‘[]‘;
}
else {
element.name = this.name_prefix + this.id++;
}
// Add reference to this object
element.multi_selector = this;
// What to do when a file is selected
element.observe(‘change’,function() {
// New file input
var new_element = document.createElement( ‘input’ );
new_element.type = ‘file’;
// Add new element
this.insert({‘before’: new_element})
// Apply ‘update’ to element
this.multi_selector.addElement( new_element );
// Update list
this.multi_selector.addListRow( this );
// Hide this
if (this.multi_selector.hidden_classname !== null) {
this.className = this.multi_selector.hidden_classname;
}
else {
this.setStyle(this.multi_selector.hidden_style);
}
});
// If we’ve reached maximum number, disable input element
if ( this.max != -1 && this.count >= this.max ) {
element.disabled = true;
};
// File element counter
this.count++;
// Most recent element
this.current_element = element;
} else {
// This can only be applied to file input elements!
alert( ‘Error: not a file input element’ );
};
};
/**
* Add a new row to the list of files
*/
this.addListRow = function( element ){
// Row div
var new_row = document.createElement( ‘div’ );
// Delete button
var new_row_button = document.createElement( ‘input’ );
new_row_button.type = ‘button’;
new_row_button.value = ‘Delete’;
// References
new_row.element = element;
// Delete function
new_row_button.observe(‘click’,function() {
// Remove item from list
this.up().remove();
// Remove element from form
this.up().element.remove();
// Decrement counter
this.up().element.multi_selector.count–;
// Re-enable input element (if it’s disabled)
this.up().element.multi_selector.current_element.disabled = false;
// Appease Safari
// without it Safari wants to reload the browser window
// which nixes your already queued uploads
return false;
});
// Set row value
new_row.update(element.value);
// Add button
new_row.insert( new_row_button );
// Add it to the list
this.list_target.insert( new_row );
};
};
Sandeep Mucherla on June 25, 2008
hi this is greate script and am using this. This works fine with IE7 adding multiple files. But this does not work in Firefox 2.0.0.14 i can only select one file at a time to upload..
Can any one help me in this issue.
michaelest on June 27, 2008
My initial experience with this code lead me to want something that was plain ‘ole javascript with consistency across multiple browsers. After stumbling across another similar implementation, I came up with…
http://www.estigoy.net/multifile
It functions in a manner very similar to this code.
All source files (HTML, javascript and PHP files – heavily commented) are available from link at the demo url (above).
I’m just venturing into advanced javascript, so please be gentle with your comments/feedback.
thanks,
Michael
Jack on July 1, 2008
Hallo!
Cool Script but how can i add a description text input field and files in the file_field from startup??
Traveller on July 10, 2008
Very cool…
But, in my opinion, will be better with a button to start the download.
Regards!
Abhilasha Sharma on July 16, 2008
Hey,
Made a minor modificationto your code so that the extension would be checked for the files to be uploaded
// Multiple file selector by Stickman — http://www.the-stickman.com
// with thanks to: [for Safari fixes] Luis Torrefranca — http://www.law.pitt.edu and Shawn Parker & John Pennypacker — http://www.fuzzycoconut.com [for duplicate name bug] ‘neal’
function MultiSelector( list_target, max )
{
this.list_target = list_target;
this.count = 0;
this.id = 0;
if( max )
{this.max = max;}
else
{this.max = -1;};
this.addElement = function( element )
{
if( element.tagName == ‘INPUT’ && element.type == ‘file’)
{
element.name = ‘file_’ + this.id++;
element.multi_selector = this;
element.onchange = function()
{
if(checkExtension(element.value)==1)
{
var new_element = document.createElement( ‘input’ );
new_element.type = ‘file’;
this.parentNode.insertBefore( new_element, this );
this.multi_selector.addElement( new_element );
this.multi_selector.addListRow( this );
this.style.position = ‘absolute’;
this.style.left = ‘-1000px’;
}
else
{alert(“Error : You can upload either microsoft word document or a pdf file only. Please check the extension of the file you are trying to upload”);}
};
if( this.max != -1 && this.count >= this.max )
{
element.disabled = true;};
this.count++;
//alert(this.count);
this.current_element = element;
}
else
{alert( ‘Error: Please choose a valid file’ );};};
this.addListRow = function( element )
{
var new_row = document.createElement( ‘div’ );
var new_row_button = document.createElement( ‘input’ );
new_row_button.type = ‘button’;
new_row_button.value = ‘Delete’;
new_row.element = element;
new_row_button.onclick= function()
{
this.parentNode.element.parentNode.removeChild( this.parentNode.element );
this.parentNode.parentNode.removeChild( this.parentNode );
this.parentNode.element.multi_selector.count–;
this.parentNode.element.multi_selector.current_element.disabled = false;return false;};
new_row.innerHTML = element.value;
new_row.appendChild( new_row_button );
this.list_target.appendChild( new_row );
};
};
function checkExtension(fileName)
{
// // for mac/linux, else assume windows
if (navigator.appVersion.indexOf(‘Mac’) != -1 || navigator.appVersion.indexOf(‘Linux’) != -1)
var fileSplit = ‘/’;
else
var fileSplit = ‘\\’;
var fileTypes = new Array(‘.doc’, ‘.pdf’ , ‘.docx’); // valid filetypes
var extension = fileName.substr(fileName.lastIndexOf(‘.’), fileName.length);
var valid = 0;
for(var i in fileTypes)
{
if(fileTypes[i] == extension)
{
valid = 1;
break;
}
}
return valid;
}
Watters on July 19, 2008
This script is great, But I’ve got a problem at the moment.
I’m using the basic script, and I don’t think it’s any php coding errors; if you choose the files, that’s fine, but if you delete files then the script does not work correctly and only uploads some files or none at all.
I would appreciate some help to see if it is actually a bug, or just an error in my code!
Watters on July 19, 2008
I worked out what was happening.
When you delete an item and add a new one, the new item takes on the next id, rather than the id of the deleted file. This caused problems with my php!
jf2008 on August 12, 2008
Try a multiple file upload applet in java:
http://www.jfileupload.com/products/jfileupload/index.html
It works with PHP script on server-side.
john on September 11, 2008
But its not AJAX!
devore2008 on September 24, 2008
Try a multiple file upload control in .NET:
http://ajaxuploader.com/Demo/select-multiple-files-upload.aspx
It looks so nice. However it’s only available in .NET version.
Can someone achieve this in PHP?
Tks.
Jagan on October 10, 2008
Hello stickman,
Thanks for the nice work.
Your code got limitation, when you set the max. number for file input elements, unless the user reaches that max number the form wont be submitted.
I am getting file not found exception from my servlet. as the file name coming as null.
my case my users dont know how many files they are uploading, so i need the form to submitted even with one file.
Thanks in advance.
Vikas on November 6, 2008
Good work
Mipi on November 14, 2008
Hello,
This is for devore2008. There are a lot of upload scripts like the one you’ve mentioned also for php. Take a look here for example:
http://www.alfafiles.com/index.php?page=inst_upload
You can find it by google for swfupload as I remember.
Reg.
heilender on November 14, 2008
action=”your_script_here.script” i don’t understand and
i want to know destination file .when i want to save file
Ajax multiupload on November 26, 2008
Hello,
I invite you to test my non intrusive multiuploader in Ajax / flash on my site http://www.nasuploader.com
cheers
mathieu on November 29, 2008
srr pasted wrong code here it is;
if(count($_FILES["file"]['name'])>0)
{
for($j=0; $j set_var(“UPLOADMSG”,”Project geupload”);
}
}
}
Vance on December 10, 2008
Thanks guys! The script works great. Just to mention for those that are new to javascript… The form submits a array. Thanks again
Anonymous on December 14, 2008
Really cool!
Michiel on December 16, 2008
Another alternative is the Silverlight Multi File Uploader, is also works with PHP. It allowes you to select multiple files from one select box.
Source code is available here:
http://www.codeplex.com/SLFileUpload
Zeshan on January 3, 2009
Very thanks for providing a nice app for uploading
v.nice
Dena Ferrera on January 7, 2009
Hello, I am using the multifile.js and am not real familar with JS. I also need to be able to check file size just like the check file types (jpg, xls etc). Any help would be greatly appreciated. I want it to check before I submit files for upload.
Thank you
Michael on January 11, 2009
Great file upload script! Compact, simple, and fairly easy to modify … However, I am having a small problem with one part:
[code]
this.addListRow = function( element ){
// Row div
var new_row = document.createElement( 'div' );
// Delete button
var new_row_button = document.createElement( 'input' );
new_row_button.type = 'button';
new_row_button.value = 'Delete';
// References
new_row.element = element;
[/code]
For each file when the script produces a “delete” it’s one of the normal horrid looking buttons … what I want to produce is this:
[code]
Save
[/code]
Can you help with out with how I might implement this?
Thanks,
Michael
Michael on January 13, 2009
I ended up making the following changes to implement better looking buttons, per this particletree post:
http://particletree.com/features/rediscovering-the-button-element/
The only problem I am having ATM is that the button drops down to the next line. If anyone can point out what i am missing I would be appreciative.
[code]
this.addListRow = function( element ){
var new_row = document.createElement( 'div' );
Element.extend(new_row);
new_row.addClassName( 'buttons' );
var new_row_button = document.createElement( 'button' );
Element.extend(new_row_button);
new_row_button.addClassName( 'positive' );
new_row_button.update('Delete ');
new_row.element = element;
[/code]
Thanks,
Michael
Michael on January 13, 2009
Oops, html does not work correctly.
This line:
new_row_button.update(’Delete ’);
should be:
new_row_button.update(‘|img src=”/dotcms/assets/images/accept.png” alt=”"/|Delete|span id=”button_span” style=”color:#C00; font-size:80%”| |/span|’);
Replace | with .
Michael
clhmedia on January 16, 2009
I’ve been trying to come with different form of multiple file uploads on my site. i think i will have to try this out in my image gallery section for anonymous users
great post
http://www.clhmedia.com
Dan on February 5, 2009
This is a fantastic control and so has worked beautifully in most browsers I tried. Thanks for the great job!
However, I just upgraded to IE8 and found that I am getting duplicate upload controls and filename in the listing when I click the Browse button after adding the first file.
Anybody encountered this and/or has a suggested fix?
Milos on February 12, 2009
I was working on a solution similar to this, using ASP .NET. I got as far as creating the input controls dynamically, but every time I posted back, I found that ASP could not find the files that I had added (via the Request.Files collection). I went online to look for help and found this page. I saw that some people had a similar problem using the scripts provided here, but no one had actually posted a solution. I ended up finding the cause of my problem, by comparing my code to the one here.
The reason ASP could not find the uploaded files was because I had not given the dynamically generated input tags a name attribute. Once I did this, the files came up just fine. I presume that this is because ASP (and most other HTTP processors) use the name attribute in the HTTP request to assign to server variables. The code provided here does add a name attribute when creating a new tag, so it may not help people using this script, but this might help anyone else out there running into similar problems.
aaa on February 13, 2009
your_script_here.script what that supposed to mean, is this some kind of fuckin joke…
Stickman on February 13, 2009
This file has been downloaded many, many thousands of times by people who have had no problem understanding that it is necessary for YOU to provide the code for handling the upload once it reaches the server. If you’re having trouble grasping that, then I suggest that this code is not for you and you should look elsewhere.
James on February 16, 2009
Hi there,
I don`t know what happened.. the first time i tried your example on this very page, it seemed to work, however after i refreshed the page, i wasnt able to do it again.
So i donwloaded your your code, and tried the example, however this neither gives me the thing i want.
My browser is: mozilla version 3.0.6
Could you tell me what`s wrong? Or is it my browser?
With kind regards, James
Sara on February 20, 2009
Oh my goodness. I think I love you! You just saved me a TON of time. Thank you, thank you and thank you. And to that person that left that other comment about this being a joke…the only joke is that you don’t know what to do with the code. Get a clue and stop biting the hand that is feeding you knowledge.
Dash on March 4, 2009
Love the script, really clever idea, a real improvement on the usual x amount of file inputs. Just one thing, I’ve noticed a few people mentioning this, I’d like the ability to add a caption with each image. I’ve also noticed a couple of comments saying they’ve achieved this, but they haven’t posted the code..? If I figure this out I’ll post it. Any help with this would be great!!
Jessie on March 6, 2009
Love the script but its not working correctly in IE8. Same problem that Dan mentioned above.
Does anyone have any suggestions?
Suresh PVS on March 6, 2009
Validation of file type has one error, when ever file type is not accepting all the previous files are also not uploading.
Please help me how to resolve this problem.
????? on March 14, 2009
thank you very usfull
Mira on March 20, 2009
Hi, Can anyone help me. I’m using the multifile.js version without any changes and it’s not working on Firefox. Not sure what’s causing that. Also I everytime I add a file I also capture the contents of a textbox. However, I only want to add the file if the textbox is not blank. How do I do this?
Marek on March 25, 2009
Hi all,
I’m having problem under IE8 with duplicate controls (like Jessie and Dan above). Is there a patch for it or any kind of solution? Anyway thank You for great job!
Steve on May 6, 2009
Hi,
Great script! Ho would i make it so you get alerted if you choose the same file twice?
Thanks
Ryan Smith on May 12, 2009
IE 8 sitll looks unstable to us. We have had many crashes when we tired our hands on IE 8.0. I will suggest to stay off, till microsoft comes with a more stable versions.
Thanks,
Ryan
Moe on May 15, 2009
Hi, this script is indeed very good, but is there a way of creating thumbs for every uploaded image?
appreciate all comments
David on June 17, 2009
I apologize for being a newbie and I’m not sure if anyone else has had this trouble but I thought I’d ask.
I downloaded the .zip file and installed code and script into my site and everything seems to work just fine. But when you click on the “Browse” button and select the file to upload, instead of listing the actual path of the file to upload (C:Documents and Settings\New Folder\My File) it displays C:\fakepath\My File.
It also lists it like this for me when I use the sample on this page.
Any ideas how I screwed this up?
Any help is greatly appreciated.
Dave
Ramon on June 26, 2009
Hi! I’m trying to implement your code inside a php website, connected with a bbdd.
My code (inside Real Estate Joomla component) it’s this:
<input class="button" type="button" value="” onclick=”if (checkForm()) this.form.submit()” />
secondaries_images as $image) : ?>
<img src="” alt=”" title=”" />
<a href="”>
**************************
I want to can select more than one image, and with your code is it possible!!!
But I don’t know how apply it inside the php code.
Can you help me??? Pleaseee!!! Thank You!!! A lot!!!
filipe abreu on June 30, 2009
thank you so much. I see that you are using the File API, as recommended by W3 (http://dev.w3.org/2006/webapi/FileUpload/publish/FileAPI.xhtml).
Have you discovered how to open a dialog box for choosing the file with javascript? The FileDialog interface is not working for me. I am doing something wrong or else it really doesn’t work?
powercords on July 1, 2009
Quote:
Hi all,
I’m having problem under IE8 with duplicate controls (like Jessie and Dan above). Is there a patch for it or any kind of solution? Anyway thank You for great job!
Ivan Thompson on July 7, 2009
Great code check my project using this idea!
Elteg on July 18, 2009
Thank you for this, I use this for my website
RM on July 22, 2009
I love you man! I have been wanting to make something like this happen on my site for ages now, but haven’t had the time to puzzle it out yet. Thanks!
James on August 7, 2009
Thanks very much for posting this. I had a use case with these exact requirements and you just saved me a tonne of work.
Online Texter Marc on August 9, 2009
Hi, i have the same problem like powercords. Is a patch available?
Tobbe on August 15, 2009
Hello,
I was just wondering if anyone could help me how the script to upload the files should look? The PHP script, the actionscript I think it’s called.
I have tried alot to build one but haven’t been able to.
Would really appreciate the help.
Bear62 on August 18, 2009
Great script, thanks so much. I had an issue with the form element in Firefox 3.0.13 completely trashing my page layout. Worked fine in IE8. On a whim I removed the comment that was within the form tag () and then it worked fine. Go figure.
Nikolaj Nørup Sostack on August 26, 2009
Hi,
Have anyone tried in a asp.net solution?
I am trying that but the Request.Files is always empty .
Any ideas?
Angie on August 26, 2009
I am trying to use this script in PL/SQL (Oracle) web development and I would like to pass the files as an array to another procedure/page — which will do the parsing and the actual submit. How would I pass the result as an array via your code? Please assist!
MarkT on September 17, 2009
Hi,
I’m embarrassingly new to all things web dev. We have an internal helpdesk system written using coldfusion. I’ve been slowly debugging and improving things.
I’m now wanting to add attachment to emails. No probs with a single file. But to dynamically add many files when you don’t know how many will be required is a bit too much of a challenge for a beginner
your multifile tool looks just what I need but – my template doesn’t pick it up and I don’t know why. the next challenge will be to find a way to store the upload filename and filepath in an array to pass to the mail sending template.
Header below
windows.addEvent(‘domready’, function(){new MultiUpload( $(‘tkaddentry’).tk_multi_attach,0,”,true,false);});
Body below
Mike on October 15, 2009
Thanks for the code dude, really helpfull
Bozhidar on October 20, 2009
Hi,
First I would like to say thanks for the great job!
The script is working fine… but I have a small(big) problem with it when I’m trying to implement it with Adobe Spry Framework 1.6.1. In particular with HTMLPanel Widget.
I have the JS link, HTML part and the initiation script in self contained html(PHP) document and if I load this in any good browser it’s working fine.
But when I try to load this file in to Spry HTMLPanel, even with globally and locally TRUE value for “evalScript” (allowed to execute content inside the HTML fragment you’re loading in to the container) it won’t initiate the “multi_selector”…
<div id="cont” class=”galleryBoxContaine”>
CONTENT IS LOADED HERE !!!!!
var container = new Spry.Widget.HTMLPanel(“cont”, { evalScripts: true });
I even try to place everything in between the container manually not loading it through Spry HTMLPanel and it is working …
So the problem is not in the page design, CSS rules but in the Spry HTMLPanel! Please if anyone has an idea of what is wrong or how can I run around to make it work I will be very thankful!
Thanks in advance!!!
Bondo2a on October 25, 2009
Hi
this is a good example but i think it has one problem about the path when i upload a file it take a fakepath and this problem happened with me and i search about the solution
Quan on November 5, 2009
Nikolaj,
You need to set the attribute runat=”server” to the file input tag to be able to retrieve uploaded file. Then in order for the client script to work correctly, you need to generate the ClientID of that server control to be used by multiSelector.addElement method.
What I used is something like this:
// Create an instance of the multiSelector class, pass it the output target and the max number of files
var multiSelector = new MultiSelector( document.getElementById( ‘ListOfFiles’ ), 3 );
// Pass in the file element
multiSelector.addElement( document.getElementById(document.getElementById(‘idHolder’).innerHTML));
The idea is to use a hidden div (idHolder) to hold the ClientID of the server file input control so that the JS script could know its client id.
And then here is the server code to save the uploaded files:
HttpFileCollection uploadedFiles = System.Web.HttpContext.Current.Request.Files;
for (int i = 0; i 0)
{
string filePath = @”C:\” + Path.GetFileName(file.FileName);
file.SaveAs(filePath);
}
}
Hope this helps!
Quan
Quan on November 5, 2009
form enctype=”multipart/form-data” runat=”server”>
input id=”fileUploadElement” type=”file” name=”fileUploadElement” runat=”server” />
input id=”uploadNow” name=”uploadNow” type=”submit” onclick=”return ExecuteUpload()” value=”Upload now” />
/form>
div style=”font-size:75%;margin-left: 10px” id=”ListOfFiles”
div style=”display:none” id=”idHolder”>
%=fileUploadElement.ClientID%>
script type=”text/javascript”>
// Create an instance of the multiSelector class, pass it the output target and the max number of files
var multiSelector = new MultiSelector( document.getElementById( ‘ListOfFiles’ ), 3 );
// Pass in the file element
multiSelector.addElement( document.getElementById(document.getElementById(‘idHolder’).innerHTML));
/script>
kevin on November 16, 2009
great script, btw, IE display the full path instead just the file name, so i have written a small script and put it under new_row_button.onclick, and replace the following line:
new_row.innerHTML = element.value;
to:
if (/msie/i.test(navigator.userAgent) && !/opera/i.test(navigator.userAgent)) {
// Set row value
var path = element.value.split(“\\”);
new_row.innerHTML = path[path.length - 1];
} else {
// Set row value
new_row.innerHTML = element.value;
}
and it works
Ian on December 5, 2009
This is brilliant, just what I needed, thanks for the great work.
I made some changes to show thumbnails in multifile_compressed.js
Line 65
Change
new_row.innerHTML = element.value;
To
new_row.innerHTML = ”;
Brilliant
Jason on December 7, 2009
Try this http://phpfileuploader.com/
Steve on December 8, 2009
Great script. I would like to limit the file size and discard if too large. How can this be done? Thanks!
Mike on December 8, 2009
Hi is it possible to store the file location to a database when a form is submitted
so I have the multi upload on a form when the user submits the form I would like to be able to store the file location to dab
thanks
Mike
Ed on December 13, 2009
Good day
When the upload image is found how do I have the image show and not the text file name.
Thank you
ED
codingstep.com on December 16, 2009
i got this error when using frame —> Notice: Undefined index: file_1 in C:\AppServ\www\….
Could you help me ?
TheOddMan on December 16, 2009
This is absolutely brilliant. I replaced the names with an array-based name and it works a charm with scripts I’m already using!
ganeshbabu on December 19, 2009
hi guys,
plz anyone help me.for how to upload muliple files,how to reading and how to find the string.plz any one help me.if know the code plz send to this mail kganeshbabu.it@gmail.com.i expect for ur replys.advance thanks.by ganeshbabu.
jfileupload on January 3, 2010
You can also try JFileUpload available at: http://www.jfileupload.com/
It allows to upload over HTTP.
Jon on January 13, 2010
Hi, I have spent alot of time on this today, I have the actual multiple browsing part work. My problem arises when it comes to uploading the files. Firstly I thought that in multiple upload cases the name of the input had to be an array, e.g. name=”example[]” but this stops the javascript from working and means you cant upload several elements. I’c tried some methods I found on these comments and have tried a few of my own, but i’m getting no where. If anyone could advice that would be great
thanks
Jon
Shyam on January 14, 2010
how can i post the elements and get its values of the input type in other page. a bit help will be appreciated.
carbon on February 8, 2010
Yeah, how do you upload with this? Where are the file locations being stored? It stores it in a java array ? How can i make php upload all the files?
Zilus on February 18, 2010
Great, I just use it and it works perfectly.
A noob tip: The file count on the uploader side, starts with 0, i.e. $_FILES[file_0][name] == my first uploaded file.
Thanks!!
Alex Cohn on February 23, 2010
Firefox 3.6, now official, supports “multiple” flag in file chooser: <input type=”file” mutiple=”" /> Opera has a slightly different format: <input type=”file” min=”1″ max=”9999″ />
Tommy on February 24, 2010
Hello,
my English is not very good. I have a question about this script. Is there a way to replace space of images after uploading it? It can also be happy before you upload them to be after you select.
Thank you very much.
Justin Wiswell on March 4, 2010
Thank you for the great script, it was very easy to implement with an existing progress bar script.
I’ve been toying with trying to add a clear all or delete /remove all function for the last day, and I have finally found a solution. Hope this helps someone else.
In the example index file, put your upload form tags inside a wrapper div.(eg form..)
after you have created an instance of the multiSelector class add this script on the same page.
[code]
//button
Clear
//function
function clearFileInputField(files_list) {
document.getElementById(files_list).innerHTML =
document.getElementById(files_list).innerHTML;
$('files_list').innerHTML='';
}
[/code]
Justin Wiswell on March 4, 2010
sorry my last post go cut off. Before the function in html code within the Div tags named uploadFile_div use this to trigger the clear all.
// a onclick=”clearFileInputField(‘uploadFile_div’)”href=”javascript:noAction();”>Clear</a
banana on March 6, 2010
Hi,
This is a great solution. I’ve been thinking to get rid of those many upload fields on my site. I tested it and for some reason when i post it like one file, there is an empty array also. like file_0, file_1 but the file_1 is empty only [error]=>4. hWhy is that? is it possible to get rid of that empty array?
Thanks
George on March 19, 2010
An excellent article for its time, but technology has come a long way since it was first written!
If you want to upload multiple files and/or images with the possibility of compression, hashing for security, image thumbnail generation/watermarking, and much more, you can’t go past UploadEase.
From a single page component you can navigate through your files and select files for uploading via a standard HTTP multipart/form-data POST request (the same as the file input element described in this article). You can even drag and drop them from external file explorers!
Don’t force your users to select files one at a time with file input elements when you can give them smart tools like UploadEase. Join the likes of Facebook, MySpace, and other sites that give their users a superior user experience.
Visit http://UploadEase.com/ today and give your users the best possible experience they can have using your website.
// Editor’s note: I’m happy for you to post this here, but I should point out that UploadEase is a commercial product (i.e. you need to purchase a licence to use it). Also…wow, people really still make Java applets these days?
kezhia on March 25, 2010
hi newbie here..good to hop on this site.
but it doesnt appear on the list those filenames uploaded.
Can u help me out to set things?im using html-freemarker,,thanks..
mail here please..kezhia04@yc
Ted on March 27, 2010
Hi, i looked through the comments for what to write in the “your script here.sript” thing, and all i see is them being rude, and you telling them to search google. can you give an example of what might go there instead? there really isnt anything to search google with… “your script here” wont turn up anything useful. Thanks!
gokul on April 1, 2010
Hi i have completed file uploaded to particular c drive location.so,how to get from c drive file to jsp page in ui(fileattachement).using jsp,servlet and extjs.
meghna on April 28, 2010
Once I upload 3 files by using this tool, where would I find them practically uploaded on the server?? How would I store it in DB?
IraQlife on May 13, 2010
Hi
this is a good example but i think it has one problem about the path when i upload a file it take a fakepath and this problem happened with me and i search about the solution
Brad on June 3, 2010
I tried putting it on my site, but it didn’t work. Could someone help me.
Brad on June 3, 2010
sorry, you can email me @ webmaster@troop93.in
Brad on June 5, 2010
I fixed the other problems, but how do I increase the max (I was hoping to have up to 15), I don’t know the first thing about JS so please help me.
Meenakshi on July 1, 2010
I need code for multiple file creation dynamically.I saw code in this website.I need dynamically that means value in multi selector will be dynamic