Wednesday, March 10, 2010

Image Upload in ASP.Net

GoDaddy web hosting is such a confusing site. My latest post about the Permission of GoDaddy folders is really not the reason why the program of Image Upload is not working.

This is the previous code:

private void SetCategoryImage(ref IProductCategory category)
{
HttpPostedFile postedImage = fuCategoryImage.PostedFile;
if (postedImage.ContentLength > 0)
{
if (postedImage.ContentType.ToUpper().Contains("IMAGE"))
{
FileInfo imageInfo = new FileInfo(postedImage.FileName);
category.ProductCategoryImage = imageInfo.Name;
category.ProductCategoryImageType = imageInfo.Extension;
category.ProductCategoryImageAltText = imageInfo.Name;
category.ProductCategoryImageCaption = txtImageCaption.Text;
fuCategoryImage.SaveAs(Server.MapPath(_catImagePath + imageInfo.Name));
}
else
{
throw new Exception("Invalid file format.");
}
}
}

While analyzing the program, it seems that there is another module which uses a different kind of image upload strategy. I tried to change this code to:

private void SetCategoryImage(ref IProductCategory category)
{
string strFileName;
string strFilePath;
_catImagePath = Server.MapPath(_catImagePath);
strFileName = fuCategoryImage.PostedFile.FileName.Replace("%20", " ");
strFileName = Path.GetFileName(strFileName);
if (fuCategoryImage.HasFile)
{
if (!Directory.Exists(_catImagePath))
{
Directory.CreateDirectory(_catImagePath);
}

strFilePath = _catImagePath + strFileName;

if (File.Exists(strFilePath))
{

}
else
{
category.ProductCategoryImage = strFileName;
category.ProductCategoryImageType = Path.GetExtension(strFileName);
category.ProductCategoryImageAltText = strFileName;
category.ProductCategoryImageCaption = txtImageCaption.Text;
fuCategoryImage.PostedFile.SaveAs(strFilePath);
}
}

}

And voila! It works!

No comments: