October 24, 2007

Uploading a file or image in C#.net and storing in a directory or a folder

Your ASPX Code will look like this:


In Ur aspx.cs just write the code on the button click

protected void Submit1_ServerClick(object sender, EventArgs e)
{
if (imageup.PostedFile != null)//Checking for valid file
{
//Since the postedfile.FileNameFileName gives the entire path we use substring functio to rip of the filename alone.
string StrImageName = imageup.PostedFile.FileName.Substring(imageup.PostedFile.FileName.LastIndexOf("\\") + 1);
string StrImageType = imageup.PostedFile.ContentType;
int IntImageSize = imageup.PostedFile.ContentLength;
//Checking for the length of the file.If Length is 0 then the file is not uploaded.
if (IntImageSize <= 0)
{
Response.Write("Uploading of Image" + StrImageName + "failed");
}
else
{
imageup.PostedFile.SaveAs(Server.MapPath(".\\upload\\"+StrImageName));
Response.Write("Your File" +StrImageName + "of type" + StrImageType +" and size"+IntImageSize.ToString() +"bytes was uploaded sucessfully");
}
img.ImageUrl = ("upload" +"/"+ StrImageName);
}
}

0 comments: