Upload and Display Images

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:

On the click of the file upload button a dialog box to select the files is displayed as:

File Upload in ASP.NET

Once the user selects the file to upload ,he can upload the file using the  UploadFiles button.The UploadFiles button is declared as:

Retrieving the posted file

The upload button click event handler calls the UploadImages method.

In the UploadImages() method ,the posted file is assigned to a byte array.

The imageData and contentType are static variables.

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.

Display uploaded Images

There are several different ways to display the uploaded images.Below we are just writing the binary array to the response.

Below the uploaded image is displayed in the browser as we are writing the image to the output stream.

File Upload in ASP.NET display image

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: