How to upload multiple files at a time

To upload a file first of all you have to set the form  “enctype” Like the given blow example.

<form id=”form1″ name=”form1″ method=”post” action=”” enctype=”multipart/form-data”>

By this Javascript user can create multiple upload box by itself

<script>
function generateRow() {
var d=document.getElementById(“div”);
d.innerHTML+=”<input type=’file’ name=’a[]’>”;
}
</script>

To upload multiples files we will take the upload box name in an array

<input type=”file” name=”a[]”>

To add new upload box we will call the JavaScript function generateRow(), which we have define above.

After click on submit button, now we will upload the files using PHP.

The whole script is:

<?php
$a=$_POST[‘a’];
// $a=count($_FILES[‘a’][‘name’]);
foreach ($_FILES[‘a’][‘name’] as $value => $key)
{
echo $_FILES[‘a’][‘name’][$value];

if (file_exists(“file/” . $_FILES[‘a’][‘name’][$value]))
{
$randFilename = uniqid(“file_”);
$_FILES[‘a’][‘name’][$value] = $randFilename.”.doc”;
move_uploaded_file($_FILES[“a”][“tmp_name”][$value],
“file/” . $_FILES[‘a’][‘name’][$value]);
}
else
{
move_uploaded_file($_FILES[“a”][“tmp_name”][$value],
“file/” . $_FILES[‘a’][‘name’][$value]);
}

}

?>
<html>
<head>
<meta http-equiv=”Content-Type” content=”text/html; charset=iso-8859-1″ enctype=”multipart/form-data” />
<title>Untitled Document</title>
<script>
function generateRow() {
var d=document.getElementById(“div”);
d.innerHTML+=”<input type=’file’ name=’a[]’>”;
}
</script>
</head>
<body>
<form id=”form1″ name=”form1″ method=”post” action=”” enctype=”multipart/form-data”>
<div id=”div”><input type=”file” name=”a[]”></div>
<input type=”button” value=”Add” onClick=”generateRow()”/>
<input type=”submit” name=”Submit” value=”Submit” />
</form>
</body>
</html>

Share This Post

Post Comment