Uploading Image Files with Entity Framework

In order to allow images to be uploaded to our website, we need to consider the most appropriate manner in which to store them. We can store images within a database, however this makes it difficult for us to create a <img> tag which points to an image file.

A better solution is to store the images in a folder. A simple approach might be to simply save the uploaded file in the directory and save the name of the file in the database, however this has one serious issue in that we will encounter a problem if two people try and upload files with the same name. There are many ways of resolving this issues, but one of the simplest is to simply rename the file using the Id of the database record.

The pseudo code for the upload process would go as follows

Example code is shown below:

protected void btnUpload_Click(object sender, EventArgs e)
    //get the extension of our image file
    string extension = (System.IO.Path.GetExtension(fileUploadControl.FileName).ToLower());
    //check the extension is valid
    if (extension == ".jpg" || extension == ".jpeg" || extension == ".png" || extension == ".gif")
        //load the image in memory so we can determine it's dimensions
        System.Drawing.Image img = System.Drawing.Image.FromStream(fileUploadControl.PostedFile.InputStream);
        int width = img.Width;
        int height = img.Height;
        //save the image data
        DatabaseEntities db = new DatabaseEntities();
        tblImage imageData = new tblImage();
        imageData.AltText = txtAltText.Text;
        imageData.Width = width;
        imageData.Height = height;
        imageData.Extension = extension;
        //assemble the filename
        string filename = imageData.Id.ToString()+extension;
        //save the image file (we could have alternatively saved the posted file,
        //but this would save any modifications we may have made to the image)
        img.Save(Server.MapPath("~/UploadedImages/" + filename));
        //inform the user
        litResult.Text = "<p>Your file was uploaded as " + filename+" in the UploadedImages folder</p>";

In order to retrieve and display the image file, we would require pseudo code as follows

Example code is shown below:

protected void Page_Load(object sender, EventArgs e)
    DatabaseEntities db = new DatabaseEntities();
    //located the image (normally we would find a specific image)
    var imageData = db.tblImages.FirstOrDefault();
    //build the filename
    string filename = imageData.Id.ToString() + imageData.Extension;
    //set the image control's attributes
    imageControl.AlternateText = imageData.AltText;
    imageControl.Width = (Unit)imageData.Width;
    imageControl.Height = (Unit)imageData.Height;
    imageControl.ImageUrl = "UploadedImages/" + filename;