Hi
Recently 2-3 people asked about how to upload and retrieve images from a folder in the web. Hence I decided to make a post on this.
The idea is to allow the user to upload the images in a folder and then show that image at a particular position. This is particularly required in an ECommerce Site. Where someone will upload the images of the Category, Product etc. The images are then stored in a folder in the web and displayed at the correct position.
First we store the Virtual path to that folder in the Web.config file. This will be helpful if we need to change the virtual path any time. We can just change it in the web.config file and there is no change in the code for that.
Just add the following line in the appsetting section
<add key="images" value="~/files/Images/" />
Now the user needs to upload the image. We will save the uploaded image in the folder (and if required the name of the image will be tagged and stored in the database).
if (!(MyFile.PostedFile == null & MyFile.PostedFile.ContentLength > 0))
{
string strPath, strpath1;
string fn = System.IO.Path.GetFileName(MyFile.PostedFile.FileName);
SaveLocation = ConfigurationSettings.AppSettings("images");
string fileName = MyFile.PostedFile.FileName;
fileName = fileName.Substring(fileName.LastIndexOf("\\") + 1);
strPath = SaveLocation + "/" + fileName;
strpath1 = Server.MapPath(strPath);
try
{
MyFile.PostedFile.SaveAs(Server.MapPath(strPath));
}
catch { }
}
Here we are saving the file in the folder name saved in the web.config file. Now we need to display this image to the user. To do this simply put the URL of the image like this.
imgShowImage.ImageUrl = ConfigurationSettings.AppSettings("images") & "NameOFImage";
Here the name of the image is the name of the image that we have stored in the database. We are taking the initial path from the folder name stored in the web.config’s appsetting.
Hope this helps
Thanks
Vikram