Upload multiple images

  • Thread starter Thread starter Rajagopal
  • Start date Start date
Rajagopal said:
Question

How to Upload multiple images in asp.net? (ex.Like a gmail file field)


Hi All,

<form id="form1" runat="server">
<input type="file" id="file_1" runat="server" /><input type="button"
onclick="addcontrol()"
value=" + " />
<div id="myDiv">
</div>
<br />
<asp:Button ID="btn_submit" runat="server" Text="Submit"
OnClick="btn_Click" />
<br />
<input type="text" value="1" id="theValue" runat="server" />
<input type="text" id="FileID" runat="server" value="1" />
<input type="text" id="GetImageURL" runat="server" />
</form>

And Also Create Javascript Function.

// Addcontrol Function Used to Dynamically Create a File field Controls
function addcontrol()
{
var ni=document.getElementById('myDiv');
var numi=document.getElementById('theValue');
var num=(document.getElementById("theValue").value-1)+2;
numi.value=num;
var divname="my"+num+"div";

document.getElementById("FileID").value=document.getElementById("FileID").value+","+num;
var newdiv=document.createElement('div');
newdiv.setAttribute("id",divname);
newdiv.innerHTML="<input type='file' id='file_"+num+"'><input
type='button' onclick=\"addcontrol()\" value=' + '><input type='button'
onclick=\"remove('"+divname+ "','"+ num +"')\" value=' - '>";
ni.appendChild(newdiv);

}

// The Following function used to Remove a File field Control

function remove(divname,val)
{
var va=document.getElementById("FileID").value.split(",");
var dd="";
for(i =0;i<va.length;i++)
{
if(va!=val)
{
dd+=va+",";
}
}
if(dd.length>1)
{
dd=dd.substring(0,dd.length-1);
}
document.getElementById("FileID").value=dd;
var d=document.getElementById('myDiv');
var olddiv=document.getElementById(divname);
d.removeChild(olddiv)
}

The Following Function used to Get image URL
function GetImageUrlText()
{
var getvalues="";
var hval=document.getElementById("FileID").value.split(",");
var len=hval.length;

for(j=0;j<hval.length;j++)
{

getvalues+=document.getElementById("file_"+hval[j]).value+",";
}
document.getElementById("GetImageURL").value=getvalues;
}

Then Go to Aspx.Cs page
You should call javascript function Page Load
btn_submit.Attributes.Add("onclick", "javascript:return
GetImageUrlText()");

The following code you put Button click(Upload Multiple Image)

protected void btn_Click(object sender, EventArgs e)
{
Array ImageUrl = GetImageURL.Value.Split(',');
for (Int32 i = 0; i < ImageUrl.Length; i++)
{
if (ImageUrl.GetValue(i).ToString() != "")
{
string StrImage = ImageUrl.GetValue(i).ToString();
string StrImageName =
StrImage.Substring(StrImage.LastIndexOf("\\") + 1);
file_1.PostedFile.SaveAs(Server.MapPath("~/images/") +
StrImageName);
}
}
}

Please Try ...
Cheers,
Rajagopal.T
 
Back
Top