How to upload a file on your website folder using ASP.NET.

How to upload a file on your website folder using ASP.NET.


Create a new webpage, use file upload control of asp.net and use the button to upload.

Design file: UploadFile.aspx


<form id="form1" runat="server">
      <div>
             <asp:FileUpload ID="fileupload" runat="server" />
             <asp:Button ID="btnuplload" runat="server" Text="upload" OnClick="btnuplload_Click" />
             <label id="lblmsg" runat="server"></label>
      </div>
</form>

Code File: UploadFile.aspx.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

public partial class UploadFile : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {

    }
    protected void btnuplload_Click(object sender, EventArgs e)
    {
        if (fileupload.HasFile)
        {
            string fileextension = System.IO.Path.GetExtension(fileupload.FileName);
            if (fileextension.ToLower() != ".doc" && fileextension.ToLower() != ".docx")
            {
                lblmsg.InnerText = "Only Files with .doc or .docx extension are allowed";             
            }
            else
            {
                int filesize = fileupload.PostedFile.ContentLength;
                if (filesize > 2097152)
                {
                    lblmsg.InnerText = "Maximum dile size (2mb) exceeded";

                }
                else
                {
                    fileupload.SaveAs(Server.MapPath("~/UploadedFiles/" + fileupload.FileName));
                    lblmsg.InnerText = "file Uploaded";
                }
            }

        }
    }
}

Explanation:
                      On the design file, I just use file upload control and button to upload a file on the web application folder.

On code file btnuplload_Click(object sender, EventArgs e) function is created
In this function, HasFile returns the boolean value that is whether control contains file or not.
further, we can also check what type of extension we want to upload here I want to upload doc file.

I also apply here size validation that is compiler can only accept file size below 2mb.

2097152 is the size in kilobytes(kb).
2*1024 = 2048
then 2048*1024 = 2097152

Server.Map: MapPath method which maps the specified relative or virtual path to the corresponding physical directory on the web server. Usually, any web server never allows accessing in any path if we don't have the proper permission.

Upload file in ASP.NET
Choose file and click the upload button




Upload file in ASP.NET

Show the uploaded file on the destination 


               



Post a Comment

0 Comments