Generating multiple upload files dynamically
I was wondering if anyone knows a better way to dynamically create an upload form?
Here is what I am trying to achieve: the code below allows uploading, I want to have a button that when clicked should add another form to upload the file. So, if I want to upload - say 7 files, I want to click the button 7 times to create these upload forms, each with its own row.
Is there anyway I can do this?
Thanks for the help:
<html>
<head>
<title> Multiple File Uploads </title>
</head>
<body>
<form enctype="multipart/form-data" action="uploader.php" method="POST">
Choose a file to upload: <input name="uploadedfile" type="file" /><br />
<input type="submit" value="Upload File" />
</form>
</body>
</html>
You usually do something like this, on the client side:
<div id='Uploadcontainer'>
<input type='file' name='uploadfiles[]' class='uploadfile' />
</div>
<button id='extraUpload'>Add another field</button>
<script type='text/javascript'>
$('#extraUpload').click(function(){
$('.uploadfile:last').clone().appendTo('#uploadContainer');
});
</script>
This is using jQuery. Then on the server side, you can easily iterate over the $ _FILES ['uploadfiles'] array:
foreach($_FILES['uploadfiles'] as $file){
//do stuff with $file
}
source to share
Here's a really very simple one, works in FireFox, Chrome and IE7. I would advise you to check a javascript framework like jQuery, it will make your life easier.
<div id='Uploadcontainer'>
<input type='file' name='uploadfiles[]' class='uploadfile' />
</div>
<button id='extraUpload' onclick="return addAnother('Uploadcontainer')">Add another field</button>
<script type='text/javascript'>
function addAnother(hookID)
{
var hook = document.getElementById(hookID);
var el = document.createElement('input');
el.className = 'uploadfile';
el.setAttribute('type','file');
el.setAttribute('name','uploadfiles[]');
hook.appendChild(el);
return false;
}
source to share
There is currently no way to do this with regular HTML. I think it is starting to get resolved in recent browsers and the upcoming HTML5 spec.
Most modern cross-browser solutions will require a JS library (and I think Flash). An alternative is to select each file separately with its own input element. For obvious reasons, browsers implement very strong protections around scripting and the display of file upload elements that can make them difficult to work with.
source to share