Introduction
This snippet allows users to add multiple files to be uploaded. By default, only one file upload control is visible. Upon clicking the "+" icon, more controls are added.
Default form
More file controls added
Background
Very often to allow multiple file uploads, an unnecessary number of file upload controls are preloaded in forms. This code is an example of how to keep the form clean
without losing the important features.
Using the Code
This code snippet is developed with PHP and needs an Apache webserver to run. The "uploads" directory needs file read-write permission. To use it in an application,
you will need to add a database interface to store the uploaded information. It is a single file that has both the form and its handler.
The script has two functions: uploadForm
and upload
. uploadForm
displays the form and upload
does the form handling.
<?php
if($_POST['pgaction']=="upload")
upload();
else
uploadForm();
?>
The above is an example for new programmers on how to deine a form and its handling in the same script.
<tr class="txt">
<td valign="top">
<div id="dvFile">
<input type="file" name="item_file[]">
</div>
</td>
<td valign="top">
<a href="javascript:_add_more();" title="Add more">
<img src="plus_icon.gif" border="0">
</a>
</td>
</tr>
The hyperlink to the icon invokes the JavaScript function _add_more
, which adds more control to the form. I have used the div
to identify a block of the form and populate more controls in this block.
function _add_more() {
var txt = "<br><input type=\"file\" name=\"item_file[]\">";
document.getElementById("dvFile").innerHTML += txt;
}
The JavaScript function adds more controls as required.
if(count($_FILES["item_file"]['name'])>0) {
$GLOBALS['msg'] = "";
for($j=0; $j < count($_FILES["item_file"]['name']); $j++) {
$filen = $_FILES["item_file"]['name']["$j"];
$path = 'uploads/'.$filen;
if(move_uploaded_file($_FILES["item_file"]['tmp_name']["$j"],$path)) {
$GLOBALS['msg'] .= "File# ".($j+1)." ($filen) uploaded successfully<br>";
}
}
}
else {
$GLOBALS['msg'] = "No files found to upload";
}
The uploaded file handler function checks for uploaded files, and if found, stores them in the web server.
Future Enhancement
In the code, if the user chooses a file and then adds more controls, the previous file information is not stored and is lost. I need to add a feature to store the previously chosen file.