RSS

Upload multiple files in asp.net with Javascript

10 Jul

Some times you need to allow user to upload as many files not fixed the number of file.then you need to use this code ,i think this help for you………

the following code use in CSS File or Header of the Aspx page

<style type=”text/css”>
.fileUpload{
width:260px;
font-size:12px;
color:#00000f;
border:solid;
border-width:2px;
border-color:#7f9db9;
height:18px;
}
</style>

Write this JavaScript  code in Header,If you want to restrict user to certain number of files then you can change your java script function as given below.

<script language=”javascript” type=”text/javascript”>
function AddMoreImages() {
if (!document.getElementById && !document.createElement)
return false;
var fileUploadarea = document.getElementById(“fileUploadarea”);
if (!fileUploadarea)
return false;
var newLine = document.createElement(“br”);
fileUploadarea.appendChild(newLine);
var newFile = document.createElement(“input”);
newFile.type = “file”;
newFile.setAttribute(“class”, “fileUpload”);

if (!AddMoreImages.lastAssignedId)
AddMoreImages.lastAssignedId = 100;
newFile.setAttribute(“id”, “FileUpload” + AddMoreImages.lastAssignedId);
newFile.setAttribute(“name”, “FileUpload” + AddMoreImages.lastAssignedId);
var div = document.createElement(“div”);
div.appendChild(newFile);
div.setAttribute(“id”, “div” + AddMoreImages.lastAssignedId);
fileUploadarea.appendChild(div);
AddMoreImages.lastAssignedId++;
}

</script>

Write this code in body tag

<div>
<div id=”fileUploadarea”><asp:FileUpload ID=”fuPuzzleImage” runat=”server” CssClass=”fileUpload” /><br /></div><br />
<div><input style=”display:block;” id=”btnAddMoreFiles” type=”button” value=”Add more images” onclick=”AddMoreImages();” /><br />
<asp:Button ID=”Button1″ runat=”server” onclick=”Button1_Click” Text=”Upload” />
</div>
</div>

Insert the following code in code behind file of page.


protected void Button2_Click(object sender, EventArgs e)
{
try
{
HttpFileCollection hfc = Request.Files;
for (int i = 0; i < hfc.Count; i++)
{
HttpPostedFile hpf = hfc[i];
if (hpf.ContentLength > 0)
{
hpf.SaveAs(Server.MapPath(“~/uploads/”) +System.IO.Path.GetFileName(hpf.FileName));
}
}
lblmsg.Text = “Sucessfully Upload”;
}
catch (Exception)
{

throw;
}
}

Advertisements
 
Leave a comment

Posted by on July 10, 2010 in Java Script

 

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

 
%d bloggers like this: