File upload to server with ASP.Net

1 minute read

File Upload to Server with ASP.net Uploading file to server from client sometimes very tricky. Sometimes it is required that you will not upload file more than certain size. This is the step by step approach to upload file from client to server.

Step 1: Add html input type as file

<input id ="uploadFile" type="file" runat="server" />

Step 2: Create a button to upload file in the server

<asp:Button ID="Button1" runat="server" OnClick="Button1_Click"  />

Step 3: Create a folder in the web project like “TempFiles”
Step 4: Upload file in the server.

protected void Button1_Click(object sender, EventArgs e)
{
 
    if (this.uploadFile.PostedFile != null)
    {
        // Get a reference to PostedFile object
        HttpPostedFile huploadFile = uploadFile.PostedFile;
        
        // Get size of uploaded file
        int nFileLen = huploadFile.ContentLength;
        
        decimal fileSize = uploadFile.PostedFile.ContentLength / 1024;
        if (fileSize > 100) //If file size is no more than 100 KB
        {
            this.lblMsg.Text = "Size of this image is greater than 100KB";
            return;
        }
        
        byte[] scriptData = new byte[nFileLen];
        
        // Read uploaded file from the Stream
        huploadFile.InputStream.Read(scriptData, 0, nFileLen);
        
        string filePath = Server.MapPath("TempFiles");
        
        filePath = filePath + "\\" + Path.GetFileName(uploadFile.PostedFile.FileName); //concate filename with file path
        FileStream newFile = new FileStream(filePath, FileMode.Create);
        
        // Write data to the file
        newFile.Write(scriptData, 0, scriptData.Length);
        
        // Close file
        newFile.Close();
    }
    else
    {
        lblMsg.Text = "This is an empty file";
    }
}