Saturday, January 19, 2008

Upload files using FileUpload control in asp.net using C#

Microsoft.Net has provided a server side asp.net control to upload files on the web server. This control is FileUpload:


Add a FileUpload control on asp.net web page. I want to upload image files so I have given this server side file upload control an id ImageUpload. You also need to add a button control which will allow you to upload the image file when it'll be clicked.


btnOK is the id of the button control which will be used in the code behind page to process the file. When you click this OK button it'll trigger btnOK_Click event, which will perform rest of the task to save the file on the server.

Also add a text box control to the asp.net page. You'll enter a name of your own choice for the image and that uploaded image will be saved with this name.

If you place a label control on the page it'll serve a purpose to show error message in case there is some exception or validation message required.

In asp.net 2.0 file upload is very easy task. Following event contains the code to upload a save the file on the server:


protected void btnOK_Click(object sender, EventArgs e)
{

if (this.ImageUpload.HasFile == true)
{
string imageName = this.txtImageName.Text;
string imageURL = this.txtImageName.Text + ".jpg";
ImageUpload.SaveAs(HostingEnvironment.ApplicationPhysicalPath + "//uploadedimages//" + imageURL);
this.txtImageName.Text = "";
this.lblMessage.Text = "Image saved successfully.";
}
else
{
this.lblMessage.Text = "Please browse file to upload.";
}
}

this.ImageUpload.HasFile will return true if the FileUpload control contains some file to be uploaded otherwise you'll show a message to request the user to select some file.

string imageURL = this.txtImageName.Text + ".jpg";

I have added .jpg extension to my custom file name because the file I have to upload is a jpg type file and I just want to save it with my specified name having the same extension.
ImageUpload.SaveAs(HostingEnvironment.ApplicationPhysicalPath + "//uploadedimages//" + imageURL);


SaveAs method of ImageUpload control saves the file on the server. HostingEnvironment.ApplicationPhysicalPath give you the physical path of your application on the web server, and UploadedImages is a folder under your root application directory. Remember if you already have a file with the same name it'll be replaced with the new file. If image is uploaded successfully the label control will show a success message.

In some later article I'll show you how to show the list of all the images on the server.


1 comment:

Unknown said...

i want to know how to display the browsed image from fileupload control on a image contol