A common requirement in web applications is to upload and display image files.There could be different scenarios for uploading and displaying the images.A requirement could be to allow the user to select the image file to upload or the file could be automatically selected on the clients machine.
Uploading the Image file
To upload the image files we can use the FileUpload server control in asp.net.This control is used to select the files on the clients machine.
We declare the FileUpload control in the aspx page as:
<asp:FileUpload ID="SelectFiles" runat="server" />
On the click of the file upload button a dialog box to select the files is displayed as:
Once the user selects the file to upload ,he can upload the file using the UploadFiles button.The UploadFiles button is declared as:
<asp:Button ID="UploadFiles" OnClick="UploadFiles_Click" runat="server" Text="Button" />
Retrieving the posted file
The upload button click event handler calls the UploadImages method.
protected void UploadFiles_Click(object sender, EventArgs e) { UploadImages(SelectFiles.PostedFile); }
In the UploadImages() method ,the posted file is assigned to a byte array.
public void UploadImages(HttpPostedFile uploadedImage) { if (uploadedImage.ContentLength > 0) { imageData = null; using (var binaryReader = new BinaryReader(uploadedImage.InputStream)) { imageData = binaryReader.ReadBytes(uploadedImage.ContentLength); contentType = uploadedImage.ContentType; } } }
The imageData and contentType are static variables.
static byte[] imageData; static string contentType;
In the above code we are just retrieving the posted file and assigning it to a variable.In a more realistic scenario we will be saving the posted file in the database.
string sql = "INSERT INTO Images(name,image) VALUES(@name, @image)"; SqlCommand cmd = new SqlCommand(sql, connection); cmd.Parameters.AddWithValue("@name",name); cmd.Parameters.AddWithValue("@image", imageData); cmd.NonQuery()
Display uploaded Images
There are several different ways to display the uploaded images.Below we are just writing the binary array to the response.
protected void displayImage_Click(object sender, EventArgs e) { Response.Buffer = true; Response.Clear(); Response.ContentType = contentType; Response.Expires = 0; Response.BinaryWrite(imageData); }
Below the uploaded image is displayed in the browser as we are writing the image to the output stream.
In a more realistic scenario we will be fetching the image from the database instead of reading from a static variable.We can read the image from the database as:
MemoryStream memoryStream = new MemoryStream(); con.Open(); SqlCommand com = new SqlCommand("select image Images from where id=1", con); byte[] image = (byte[])command.ExecuteScalar(); stream.Write(image, 0, image.Length);