Search Asp.Net Here

Add FileUpload Control at runtime in asp.net using javascirpt




Add dynamic FileUpload Control at runtime in asp.net using javascirpt



In our projects there may be a situation at design time where we don’t know how many FileUpload control we need in a web page. So we have to add FileUpload Control at runtime as much as user of our page requires.
In this post I am showing you how to add File upload Control at runtime in asp.net
We will use javascript to add FileUpload control at runtime and than save the files uploaded by the user.

JavaScript code to add FileUpload control at runtime

var i = 1;
function AddFile()
{
i++;
var div = document.createElement('DIV');
div.innerHTML = '<input id="file' + i + '" name="file' + i + '" type="file" /><img alt="Remove" onclick="RemoveFile(this)" src="Images/delete.jpg" />';
document.getElementById("divFile").appendChild(div);
}
function RemoveFile(file)
{
document.getElementById("divFile").removeChild(file.parentNode);
}
I have created two methods for adding and removing FileUpload at runtime. AddFile() method will add a FileUpload control and a remove button. RemoveFile(file) method will remove the FileUpload control if added by mistake.


HTML or .ASPX page code

<form id="form1" runat="server" enctype="multipart/form-data" >
<div id = "divFile">
<input id="file1" name = "file1" type="file" />
<!--FileUpload Controls will be added here -->
</div>
<br />
Add More Files  <img src="Images/add.jpg" alt="Add more files" onclick="AddFile()" /><br /><br />
<asp:Button ID="Button1" runat="server" Text="Upload" OnClick="Button2_Click" />
</form>

Code for .cs file


protected void Button2_Click(object sender, EventArgs e)
{
for (int i = 0; i < Request.Files.Count; i++) { HttpPostedFile PostedFile = Request.Files[i]; if (PostedFile.ContentLength > 0)
{
string FileName = System.IO.Path.GetFileName(PostedFile.FileName);
PostedFile.SaveAs(Server.MapPath(".//") + FileName);
}
}
}

To get the all files selected by the web form user, we are using the Request.Files, which will return a collection of files. we loop through Collection of Request.Files and assinging each file to HttpPostedFile object and saving file with SaveAs() method of the HttpPostedFile class.

Download Source Code



Comments :

3 comments to “Add FileUpload Control at runtime in asp.net using javascirpt”
Devendra said...
on 

fdfdfdf

Anonymous said...
on 

really vary fine code..
it works in very correct manner....

Anonymous said...
on 

Nice Code,Easy to understand it

Post a Comment