Proxy > Gmail Facebook Yahoo!

ASP.NET Photo Album Part 2 - Adding Images




ASP.NET Database Tutorial

This is the second part of the ASP.NET Photo Album tutorial series. This tutorial will walk you through the steps of creating a form that will allow a user to upload images to the database with ASP.NET 4.0 and C#.


Adding the Add.aspx Page
At this point, we should have our datbase setup and be ready to add in a form that will allow users to upload images. To begin:

  1. Right click the project in your solution explorer.
  2. Select add new item...
  3. Select a web form.
  4. Name it 'Add.aspx'.
  5. Click add.
You are reading My Code Logic.
Next, we need to add in a form that will allow the user to upload an image and give us the information they need such as the date and message. Build a form that looks like this:



First, I added a link to the top of this page that says 'Home' and links to the Default.aspx home page that we will add later. Then, I have created a simple table and have added in a fileupload control named 'fupImage' with a customvalidator next to it that we will add some functionality to later. Then, I added in a textbox named 'txtMessage'. Next, I added in a calendar control with a textbox named 'txtDate' that we will add some functionality to allow the user to select a date from the calendar, and have that date be set to the date textbox. Finally, I added in a button named 'btnUpload'. To view the source of this form, download the project here.
You are reading My Code Logic.
Next, we just need to add in some code to allow our form to function properly. First, to make the calendar populate our date textbox, add in the following code in the event that the calendar's selection is changed:
//display newly selected date in our textbox
txtDate.Text = calDate.SelectedDate.ToShortDateString();


Then, we need to add some functionality to the custom validator that we added. In this example, we will allow the user to only upload the following file types: 'jpg', 'jpeg', 'png', 'gif', and 'bmp'. To add our validation, add the following code in the ServerValidate event of our custom validator:
//create an array of valid file extensions
string[] validExt = { "jpg""jpeg""png""gif""bmp"};
//set args to invalid
args.IsValid = false; 
//get file name
string fileName = fupImage.PostedFile.FileName;
//check to make sure the string is not empty
if (!string.IsNullOrEmpty(fileName))
{
    //get file extension
string fileExt = fileName.Substring(fileName.LastIndexOf('.') + 1).ToLower();
   //check if current extensions matches any valid extensions
   for (int i = 0; i < validExt.Length; i++)
   {
       if (fileExt == validExt[i]) //if we find a match
           args.IsValid = true;    //validate it
   }
}


Next, add in the following code in the event the upload button is clicked, to store our image data in our database: You are reading My Code Logic
//check to make sure a file is selected before adding it to the db
if (fupImage.PostedFile != null)
if(!string.IsNullOrEmpty(fupImage.PostedFile.FileName) && CustomValidator1.IsValid))
{
    //create a byte array to store the binary image data
    byte[] imgBin = new byte[fupImage.PostedFile.ContentLength];
    //store the currently selected file in memeory
    HttpPostedFile img = fupImage.PostedFile;
    //set the binary data
    img.InputStream.Read(imgBin, 0, (int)fupImage.PostedFile.ContentLength);
    //connect to the db
    SqlConnection conn = new 
SqlConnection(WebConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString);
    //sql command to save our image data to the db
SqlCommand cmd = new SqlCommand("INSERT INTO Images(ImgBin, ImgSize,"_
+ ImgType, ImgDate, ImgMessage) VALUES (@ImgBin, @ImgSize, @ImgType, @ImgDate,"_
+ @ImgMessage)", conn);
    cmd.CommandType = CommandType.Text;
    //add img binary data
cmd.Parameters.Add("@ImgBin"SqlDbType.Image, imgBin.Length).Value = imgBin;
    //add img size
cmd.Parameters.AddWithValue("@ImgSize", imgBin.Length);
    //add img type
cmd.Parameters.AddWithValue("@ImgType", fupImage.PostedFile.ContentType);
    //add img date
cmd.Parameters.AddWithValue("@ImgDate"DateTime.Parse(txtDate.Text));
    //add img message
cmd.Parameters.AddWithValue("@ImgMessage", txtMessage.Text);
    using (conn)
    {
        //open the connection
        conn.Open();
        //send the sql query to store our data
        cmd.ExecuteNonQuery();
    }
}


Testing
To test this out, simply load up the web site, fill out the form, select a file, and click upload. Then, ensure that the image data was properly added to the database.



Responses

0 Respones to "ASP.NET Photo Album Part 2 - Adding Images"


Send mail to your Friends.  

Expert Feed

 
Return to top of page Copyright © 2011 | My Code Logic Designed by Suneel Kumar