image upload,resize and save.

Every day users upload millions of images to web sites allover the world. So image uploading is an every day task for any ASP.NET developer. Handling uploaded images is an easy task which we will discuss in this article. We will follow my sweet philosophy in programming which is trying to minimize the code writing as possible and try to do every thing in the declarative easy way and the result code should work well for small to medium websites.

Handling image upload in

we will imagine that we are preparing an website where the  user can submit  his name,address,phone number and sure  his image to be stored on our data base ,What is the steps to accomplish the task?

  • First we have the add new user page:

1-Sending the image from the client browser to our server (Sure the file should be validated for type and size to avoid security and performance problems).

2-Storing the record that contains the employee information the database (access database in our case) including the image path that we choose. (We will explain later that the image path has to be renamed).

3-Resize the image or create thumbnail from the image if needed.

4-Saving the customized image to the folder we specify on the server with the same new file path that we stored in the data base record,So we can call it again to be presented on data bound image control .If the name of the uploaded image on the file system was different from that we stored on the database the image won’t be found and will leave an ugly red x mark on the final data presentation page.

5-Inform the employee if the image uploading and data recording is finished or there are problems.

  • Then we have the update page where the user can update his profile info:

Which have the general requirement like previous plus that we have to check if the user want to change his profile image. If the user want to change the image he will choose another image then we have to upload the new  image,update the data base with the new name,save the new image to the images folder then delete the old image not to waste disk space.

  • then we have the delete user page:

from this page the site admin can delete any user from the data page then after delete the code should search for the deleted user image and delete it also

ASP.NET upload image code highlights:

As I want even the beginner developers to be able to use this code to handle uploaded images. I will describe some important points before starting the step by step tutorial

  • Insert page code highlights:

All the images uploaded by employees will be stored in the same folder on the server. Imagine that an employee uploaded an image named (mypicture.png) then after an hour another employee uploaded another image with the same name also (mypicture.png) what will happen?? The server will simply replace the old image with the new one. Then when the first employee opens his profile page he will find another person’s image presented as his image. Sure he will feel that the person who coded this site is drunk or trying to be funny.So how we will solve this problem?1-First we will declare 2 page level string variables to store the new image file path also the thumbnail image file path (we used page level variables here because it can retain it’s same value between different staged of page life cycle so the image path that will be stored to the data base will still the same when we save the images to the server). 2-store to these variables some unique string value that very hard to be repeated like logged employee id which can’t be repeated or the current time millisecond + second + minute ,the purpose of this step is to be sure that each image will have a unique file name that can’t repeated .

Dim filenamelarge As String = “~/employeeimg/” & DateTime.Now.Millisecond.ToString &DateTime.Now.Second.ToString &DateTime.Now.Minute.ToString

Dim filenamethumb As String = “~/employeeimg/” & “thumb” &DateTime.Now.Millisecond.ToString &DateTime.Now.Second.ToString &DateTime.Now.Minute.ToString


Inherits System.Web.UI.Page


3-on formview item inserting event handler read the uploaded image file path that contains the image extension from the image upload control then add it to the page level variables after the unique value we generated above,we are doing so to make the images file path readable to humans for any purpose also to add the image extension from the uploaded image.

Dim fileuploader1 As FileUpload =DirectCast(FormView1.FindControl(“fileUpload1″),FileUpload)

If fileuploader1.HasFile Then

filenamelarge = filenamelarge  &(fileuploader1.FileName)

filenamethumb = filenamethumb &(fileuploader1.FileName)


filenamelarge1 = “”

filenamesmall1 = “”

End If

Here we first find our fileupload1 control that located inside the formview using the findcontrol function then we then we cast it to a file upload type variable so we can access its proprieties Then we check if the employee chooses a file to upload if yes we change auto generated filename by adding the uploaded image filename.4-on the formview item inserting event handler we will inject the new image path we generated and the thumbnail image file path as an access data source parameters values to be stored to the data base with the rest of data.

Dim myaccesdatasource As SqlDataSource = addproduct

mysqldatasource.InsertParameters(“image”).DefaultValue = filenamelarge

mysqldatasource.InsertParameters(“thumbnail”).DefaultValue = filenamethumb

where image and thumbnail are the columns names of where we want to store the uploaded image and thumbnail  image filepath

5- On the item inserted event handler of the formview we will resize the image,create thumbnail and finally save it to the folder we want with the same names that stored to the data base. There are too many classes available on the internet to resize the images and create thumbnails from the uploaded images. I will work here with a very good class from the( ASP.NET 2.0 instant results) book from Wrox you can buy the book ,it is really great book or just download the code for free including this imageresize class from Wrox website. I won’t write it here because I don’t want to violate the copyrights of the book authors.The class accepts three arguments the first is the name of the original file,the second is the name you want to give to the new resized image,the third one is the final image size in pixels.  imageresizer.ResizeImage(Server.MapPath(filenamelarge),_                        Server.MapPath(filenamethumb),100) This code snippet take the original image file path create thumbnail and save it with the new filenamethumb valueAlso if we want to resize the uploaded image we just pass the filenamelarge and resize it and save it with its image file path and the server just replace the original uploaded image with the new resized version as both have the same exact filename.Like this  imageresizer.ResizeImage(Server.MapPath(filenamelarge),_                        Server.MapPath(filenamelarge),500)The resized images with this class have acceptable quailty and much more less file size but if you need a higher quality of the resized image you should consider bying a third party image resizing softwere.

  • The update page code highlights:

All the code snippest that we used in the add new record page will be used plus checking if a new image is uploaded from the employee to update the data base and delete the old originial image ant old thumbnail then save the new image and generated thumbnail.We will employee the file.delete function to delete the old image and thumbnail after reading their file paths from databound controls inside the formview . This function accept the full physical path of the file we want to delete(like d:/websites/ourwebsite/wwwroot/employeesimages/employee1.png) and delete it for us. Now we have a trouble we don,t know the physical path of the uploaded saved image on the server,we know only the relative path of these images to our application root (like ~/employeesimages/employee1.png). We will solve this by using the server.mappath function wich convert the relative file path to physical file path that can be used in file operations.     File.Delete(Server.MapPath(oldimageurl))

  • Delete employee page:

We will simply delete the image and thumbnail using the same file.delete function in the gridview rowdeleting event handler after getting image and thumbnail file paths from data bound literal controls inside the gridview item template.

ASP.NET image upload tutorial:

We will work here with vwd 2008 sp1,.net framework v 3.5 but the steps should work for all vs or vwd versions from 2005 or above and also can work on .net framework 0.2  Now we will start to create our demo website from scratch step by step also the full demo will be available to download. 1. Create new wesite named image_upload:from the vwd 2008 file menu >>newwebsite >>from vwd templates choose website and the language to >>change the name and location like you want2. Create new sql data base:from the vwd website menu choose add new item >>from the templates choose sql server data base >>name it “imageuploaddata” >> then click ok to add the new data base to your app_data folder.3. Create the  data table:from the vwd solution explorer window expand the app_data folder node you supposed to find the  “imageuploaddata “ data base you added  >> then double click on the data base to open the vwd database explorer window >> from the vwd database explorer window expand “imageuploaddata “  node  >>then right click on the tables node and choose add new table4. Design the “imageupload_emptable” table: for priefcy we will create the table with only four columns  empid,empname ,empiamge and empthumb >>In the desiger insert the table names as After creating the table rows select the “empid” column and press  the small golden key on the upper left side of vwd window to set the empid column as a primary key of the table >>then in the column properties section on the table designer find the “identity specification” node and extend it >>then we have to set the primary key cloumn as an autoincremented field for example 1,2,3,4 to give unique value for each record to do so find the (is identity) properity set it to yes and leave the seed and increment unchanged >>then close the table designer tap >>choose yes to save the changes >>name the new table “imageupload_emptable” then click ok5- create an empty folder named “empimages” to store the uploaded images to5. Create the “image_upload_insert.aspx” page: From the website menu choose “add new item” >>from the vwd templated choose “webform” name the page “image_upload_insert.aspx” then click okDesigning the image upload insert page:

  • Designing  the image_upload_insert.aspx:

Creating the sqldatasource:Open the “image_upload_insert.aspx”  page if it is not opened then switch to the design view  >>from the toolbox drag “sqldatasource” contol and drop it to the page.This will be respnsible for the connection between the data base and the formview that we will add later >> From the task menu (the small arrow on the right of the sqldatasource)  choose “configure data source”  >> you will be asked to choose the data connection ,Just chose the “imageuploaddata.mdf “ from the list and click next >>you will be asked if you want to save this connection to you web.config file so you can use it any time ,name It “image_upload_conec” and click next >>then from the next window choose the “imageupload_emptable” table we created before check on the four fields we created before empid empname empimage empthumb >>then click on the advanced button and check on create delete update and delete button  >>then click next >>on the next window click finishThe designer will add this code to your page

asp:SqlDataSource runat=”server”


DeleteCommand=”DELETE FROM [imageupload_emptable] WHERE [empid] = @empid”

InsertCommand=”INSERT INTO [imageupload_emptable] ([empname],[empimage],[empthumb]) VALUES (@empname,@empimage,@empthumb)”

SelectCommand=”SELECT [empid],[empname],[empimage],[empthumb] FROM [imageupload_emptable]”

UpdateCommand=”UPDATE [imageupload_emptable] SET [empname] = @empname,[empimage] = @empimage,[empthumb] = @empthumb WHERE [empid] = @empid”>

Notice the connection string we choosed above and then the sql comannds for the CRUD (create update and delete) operations  then the parameters section ,also note that the designer didn’t mentioned the empid in the insert sql command and the insert parameters why?? Because it is an autoincrenebted field wich will be added automatically by the data base.

Creating the image upload form view :D rag a formview from the toolbox to the page >>from its task menu choose the sql data source we created above “image_upload_insert_datasource” >>then press “refresh schema ” to generate the item,insert and update templates of the formview automatically based on the sqldatasource fields,We will customize these templates to fulfil our needs but as a beginners it is a good start to have part of the work done by the vwd >>from the task menu choose the edit templates button >>then from the generated ddl  choose to diplay ”insert item template” >>we will find the formview insert item template look like this  Now we have to customize it because infront of the empimage and empthumb  there are two textboxes the vwd added this text boxes because it finds that these fields accept string values in the sqldatasource parameters ,the vwd don’t know that we will need to upload images and save the images names  to these fields in the data base >>we will remove the text boxes infront of empimage and empthumb >>and also remove the empthumb text itself because the user will upload only one image from the empimage field and the thumbnail will be generated and named dynamically >> aslo we will remove the cancel button because it will be an insert only page >>now drag fileupload control from the toolbox and drop it inside the formview insert template beside the empimage text chane its id to “image_upload_fileuploader”  >>then from the task menu choose “end template editing”  >> last thing wich is very important  from the formview properties window find the “default mode” and change it to “insert”,this will make the formview open when the page load in the insert mode not the default read only mode >>now we have no more work to be done here

  • here is the full codebehind page:

    ‘first declare the page level variables to store the image and thumbnail file path between
    ‘item inserting and item inserted events of the fromview to make sure that the file path
    ‘that is stored to the data base is the same that will be used as a filename for the uploaded image’we add the millisecond second and minute in the begining of image and thumbnail files names to be
    ‘sure that there won’t be duplicate files
    Dim image_namelarge As String = “~/empimages/”&_
    DateTime.Now.Millisecond.ToString &DateTime.Now.Second.ToString &DateTime.Now.Minute.ToString
    Dim image_namethumb As String = “~/empimages/”&“thumb”&_
    DateTime.Now.Millisecond.ToString &DateTime.Now.Second.ToString &DateTime.Now.Minute.ToString

    protected Sub Page_Load(ByVal sender As Object,ByVal e As System.EventArgs) Handles Me.LoadEnd Sub

    Protected Sub FormView1_ItemInserting(ByVal sender As Object,_
    ByVal e As System.Web.UI.WebControls.FormViewInsertEventArgs) _
    Handles FormView1.ItemInserting’Here we first find our fileupload1 control that located inside the formview using the
    ‘findcontrol function then we then we cast it to a file upload type variable so we can access
    Dim fileuploader As FileUpload = DirectCast(FormView1.FindControl(“image_upload_fileuploader”) _
    ‘then check if the user want to upload an image
    If fileuploader.HasFile Then
    ‘now we add the uploaded image extension to the autogenerated name
    image_namelarge = image_namelarge + Path.GetExtension(fileuploader.FileName)
    image_namethumb = image_namethumb + Path.GetExtension(fileuploader.FileName)
    ‘or store empty vlaue if the user didn’t uploaded any images
    image_namelarge = “”
    image_namethumb = “”
    End If  ‘we inject the thumnail file path and the image file path as a parameters default values
    ‘of our data sourceimage_upload_insert_datasource.InsertParameters(“empimage”).DefaultValue = image_namelarge
    image_upload_insert_datasource.InsertParameters(“empthumb”).DefaultValue = image_namethumb
    End Sub

    Protected Sub FormView1_ItemInserted(ByVal sender As Object,ByVal e As System.Web.UI.WebControls.FormViewInsertedEventArgs) Handles FormView1.ItemInserted
    ‘remember that the page level variables still have the last version of file paths used in
    ‘item inserting event above.
    ‘we can still use it here’Here we first find our fileupload1 control that located inside the formview using the
    ‘findcontrol function then we then we cast it to a file upload type variable so we can access
    Dim fileuploader As FileUpload = DirectCast(FormView1.FindControl(“image_upload_fileuploader”),_
    ‘check if the database insert is done by checking number of affected rows
    If e.AffectedRows >0 Then
    ‘then check if the file uploader has file
    If fileuploader.HasFile Then
    ‘save the original image using the file upload save as method
    ‘also converting relative path to physical path using server.mappath function
    Try’Now resize the original image and overwrite the originalwith the resized
    ‘then create thumbnail and save it also
    End TryEnd If’if every thing is ok hide the formview
    FormView1.Visible = False
    ‘inform the user that insert is done
    Panel2.Visible = True
    Label1.Text = “insert is done ”
    ‘if a problem happened also hide the form view
    FormView1.Visible = False
    ‘and inform the user to come back later ,sure not a good error handling
    ‘but error handling is not the issue here
    Panel2.Visible = True
    Label1.Text = “sorry,an error happend please try again later”End If
    End Sub

    Protected Sub LinkButton2_Click(ByVal sender As Object,ByVal e As System.EventArgs) Handles LinkButton2.Click
    ‘if the user need to add another item we will just make the formview visible again
    ‘and data bind it to clear the text box.
    Panel2.Visible = False

    FormView1.Visible = True
    FormView1.DataBind()end subend class

  • i will cotinue the update and delete pages in a few days



Share and Enjoy:
  • Print
  • Digg
  • Sphinn
  • Facebook
  • Mixx
  • Google Bookmarks
  • Blogplay
  • DotNetKicks
  • Yahoo! Bookmarks
  • LinkedIn
  • Live
  • MySpace
  • Technorati
  • Twitter

23,757 comments to image upload,resize and save.

Leave a Reply




You can use these HTML tags

<a href=""title=""><abbr title=""><acronym title=""><b><blockquote cite=""><cite><code><del datetime=""><em><i><q cite=""><strike><strong>