Multiple-file uploads

I have been a big fan of Basecamp since it first came out. One of the
nice things about the Message model in that “weblication” is the
support for attaching multiple files to a message. They’re not relying
on a Flash widget – it’s just normal file inputs – but you never
“run out” of inputs. Rather than giving you 4 fields or 40, they just
give you another one each time you select a file to upload. It’s very
neat, so I decided to see if I could imitate it.

They’re using much nicer, Class-based code in theirs, but mine works
pretty well for a declarative style. The trick revolves around moving
file inputs off-screen after they have been filled. This is done by
observing the field’s ‘onchange’ event, which fires when the file
field gets populated with a file for upload. So when that happens, the
field gets moved from one UL to another. That second UL is inside the
same form as the first, but it is positioned with CSS 10,000 pixels
above and left of your screen.

If you click the “Show Offscreen Elements” link, you can watch this
happen in real time. All this does is move the element back into the
page where it started.

http://scripty.walterdavisstudio.com/files.php

All the JavaScript and CSS code is inline so you can dissect it. The
PHP code is a simple multiple file handler, and all it does is accept
any file upload and pipe it to /dev/null. Your code would naturally
store the uploaded files somewhere.

The heart of it (and indeed of handling any multiple-file upload in
PHP) is this loop:

foreach($_FILES['userfile']['name'] as $key=>$name){
	$basename = safe_name(basename($_FILES['userfile']['name'][$key]));
	if (move_uploaded_file($_FILES['userfile']['tmp_name'][$key], '/dev/ 
null/')) {
		$out .= '<li>' . $basename . '</li>';
	}
}

(safe_name() is my function that strips anything besides
alphanumerical characters and dots out of filenames, replacing them
with underscores – not a built-in PHP thing.)

Give it a try, and use this pattern in your own applications.

Walter


dynamo mailing list
email@hidden
Update your subscriptions at:
http://freewaytalk.net/person/options