Tuesday, September 22, 2015

Fileupload control in asp.net

Suggested Videos
Part 19 - Mapping virtual path to physical path using Server.MapPath method
Part 20 - Mapping virtual path to physical path using Server.MapPath method Example

In this video we will discuss about fileupload control. FileUpload control is a combination of a text box and a browse button that enable users to select a file to upload to the server.

Create an asp.net web application project. Drag and drop the FileUpload control on the webform.



The fileUpload control only allows the user to select the file. To upload the seleceted file, drag and drop a button control. Change the ID of the button to btnUpload and the Text to Upload File. Also drag and drop a label control, and change the ID of the label to lblMessage. At this stage the HTML of the webform should be as shown below.
<asp:FileUpload ID="FileUpload1" runat="server" />
&nbsp;
<asp:Button ID="btnUpload" runat="server" Text="Upload File" 
    onclick="btnUpload_Click" />
<br />
<asp:Label ID="lblMessage" Font-Bold="true" runat="server">
</asp:Label>



Right click on the web application project and add a folder with name Uploads. This folder is going to store all the uploaded files. 

Copy and paste the following code in btnUpload_Click() event handler
// If the user has selected a file
if (FileUpload1.HasFile)
{
    // Get the file extension
    string fileExtension = System.IO.Path.GetExtension(FileUpload1.FileName);

    if (fileExtension.ToLower() != ".doc" && fileExtension.ToUpper() != ".docx")
    {
        lblMessage.ForeColor = System.Drawing.Color.Red;
        lblMessage.Text = "Only files with .doc and .docx extension are allowed";
    }
    else
    {
        // Get the file size
        int fileSize = FileUpload1.PostedFile.ContentLength;
        // If file size is greater than 2 MB
        if (fileSize > 2097152)
        {
            lblMessage.ForeColor = System.Drawing.Color.Red;
            lblMessage.Text = "File size cannot be greater than 2 MB";
        }
        else
        {
            // Upload the file
            FileUpload1.SaveAs(Server.MapPath("~/Uploads/" + FileUpload1.FileName));
            lblMessage.ForeColor = System.Drawing.Color.Green;
            lblMessage.Text = "File uploaded successfully";
        }
    }
}
else
{
    lblMessage.ForeColor = System.Drawing.Color.Red;
    lblMessage.Text = "Please select a file";
}


If you are searching life partner. your searching end with kpmarriage.com. now kpmarriage.com offer free matrimonial website which offer free message, free chat, free view contact information. so register here : kpmarriage.com- Free matrimonial website