Thursday, July 3, 2008

File Upload

when You call the AddImage Method first it will check the value of FileUpload contrlol if it has the postedfile its call the mehtod (UploadImage(FileUpload1.PostedFile.FileName, FileUpload1))
...............
this code is the suitable for saving the images in the Image Folder & it's return the image name.

private string AddImage()
{
string strFilename = "";

if ((FileUpload1.PostedFile == null || FileUpload1.PostedFile.ContentLength == 0))
{
strFilename = "";
}
else
{
strFilename = UploadImage(FileUpload1.PostedFile.FileName, FileUpload1);
}

return strFilename;
}


private string UploadImage(string filePath, FileUpload fileUpload)
{
string strFilename = "";
try
{
strFilename = System.IO.Path.GetFileName(filePath);
Random rnd = new Random();
int prefix = rnd.Next();
strFilename = prefix.ToString() + strFilename;

string path = Server.MapPath("~");
string fullPath = path + "/" + "images";

DirectoryInfo dirinfo = new DirectoryInfo(fullPath);
if (dirinfo.Exists)
{
string strFilePath = fullPath + "\\" + strFilename;
fileUpload.PostedFile.SaveAs(strFilePath);
}
else
{
dirinfo.Create();
string strFilePath = fullPath + "\\" + strFilename;
fileUpload.PostedFile.SaveAs(strFilePath);
}

}
catch (Exception ex)
{
Response.Write(ex.ToString());
}

return strFilename;
}

No comments: