Multiple file upload |
This code contains the form with the file field, add and remove button and of course, the upload button. jQuery is used for its dynamic adding or removing of file fields.
<html>
<head>
<title>How To Add or Remove File Field Then Upload File in PHP and jQuery</title>
</head>
<body>
<?php
isset($_REQUEST['action']) ? $action = $_REQUEST['action'] : $action = '';
if( $action == 'uploadfiles' ){
//define where the files will be uploaded
$upload_directory = 'uploads/';
$x=0;
echo "</div>Uploaded Files:</div>";
foreach ( $_FILES['data']['name'] AS $key => $value ){
echo "<div>{$value}</div>";
//Move file to server directory
move_uploaded_file($_FILES["data"]["tmp_name"][$x], $upload_directory . $_FILES["data"]["name"][$x]);
$x++;
}
}
?>
<form enctype="multipart/form-data" action="#" method="POST">
<input type="hidden" name="MAX_FILE_SIZE" value="100000" />
<div>Choose a file to upload:</div>
<div id="text">
<div ><input name="data[]" type="file" /></div>
<!-- This is where the new file field will appear -->
</div>
<input type="button" id="add-file-field" name="add" value="Add input field" />
<input type='hidden' name="action" value="uploadfiles" />
<input type="submit" value="Upload File" />
</form>
<script type="text/javascript" src="js/jquery-1.6.1.min.js"></script>
<script type='text/javascript'>
$(document).ready(function(){
// This will add new input field
$("#add-file-field").click(function(){
$("#text").append("<div class='added-field'><input name='data[]' type='file' /><input type='button' class='remove-btn' value='Remove Field' /></div>");
});
// The live function binds elements which are added to the DOM at later time
// So the newly added field can be removed too
$(".remove-btn").live('click',function() {
$(this).parent().remove();
});
});
</script>
</body>
</html>
The Code of a Ninja Resources
For FREE programming tutorials, click the red button below and subscribe! :)
website