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!

Wednesday, March 3, 2010

GoDaddy Issues

FileUpload Permissions

In GoDaddy web hosting, the permission in all the files in the website are defaulted to Read Access.

If ever your site has FileUpload controls, you might encounter this kind of error:


Request for the permission of type System.Security.Permissions.FileIOPermission, mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 failed.


You need to change the Permission of the folders of your files to Read and Write Access, so it will be allowed to upload the files in your site.