Tuesday, May 5, 2009

Multiple file upload

My last blog
just talked about adding and removing file upload controls in html.

Here is the code to upload multiple files to server along with the adding file upload control using javascript.

Copy and paste the below lines in aspx page between form tags:

<input type="file" name="attachment" runat="server" id="attachment" onchange="document.getElementById('moreUploadsLink').style.display =
'block';" />
<div id="moreUploadsLink" style="display:none;">
<a href="javascript:addElement();">Attach another File</a>
<input type="hidden" value="0" id="theValue" />
<div id="myDiv"> </div>
<asp:Button ID="Button1" runat="server" Text="Upload" onclick="Button1_Click" />

Copy and paste the below javascript:
<script type="text/javascript">
function addElement()
var ni = document.getElementById('myDiv');
var numi = document.getElementById('theValue');
var num = (document.getElementById('theValue').value -1)+ 2;
numi.value = num;
var newdiv = document.createElement('div');
var divIdName = 'my'+num+'Div';
newdiv.innerHTML = '<input type="file" name="attachment" id="attachment"/><input type="Button" value="Remove" onclick="removeElement(' + divIdName
+ ')"/>';

function removeElement(divNum)
var d = document.getElementById('myDiv');


Copy and paste the below code in the code behind:
protected void Button1_Click(object sender, EventArgs e)
HttpFileCollection uploadFiles = HttpContext.Current.Request.Files;
for (int i = 0; i < uploadFiles.Count; i++)
HttpPostedFile uploadFile = uploadFiles[i];
uploadFile.SaveAs(@"c:\inetpub\wwwroot\" + Path.GetFileName(uploadFile.FileName));

1 comment:

Anonymous said...

hello sir,
i am using VS 2005, asp.net 2.0,
i used this script to upload multiple files but delete button is not working. Please suggest me the solution asap.
Thank you in advance.

Site Meter