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:
i want to know how to display the browsed image from fileupload control on a image contol
Post a Comment