How to Upload Files in ASP.NET


ASP.NET 4.0 comes with a FileUpload control that allows you to send a file from your computer to a Web server. The file to be uploaded is submitted to the server as part of the browser request during postback. After the file has completed uploading, you can manage the file in your code.

1. Create an ASP.NET project in Visual Studio 2010.

2. Drag and drop a FileUpload control on Web Form.

3. Write this code on the Page Load event of the Web Form. You need to make sure your folder on the Web Server is set to a valid directory and have write permissions on it.

protected void Page_Load(object sender, EventArgs e)
{
    if(IsPostBack)
    {
        Boolean fileOK = false;
        String path = Server.MapPath("~/UploadedFilesFolder/");
        if (FileUpload1.HasFile)
        {
            String fileExtension =
                System.IO.Path.GetExtension(FileUpload1.FileName).ToLower();
            String[] allowedExtensions =
                {".gif", ".png", ".jpeg", ".jpg"};
          for (int i = 0; i < allowedExtensions.Length; i++)
          {
               if (fileExtension == allowedExtensions[i])
               {
                    fileOK = true;
               }
          }
        }

        if (fileOK)
        {
            try
            {
                FileUpload1.PostedFile.SaveAs(path
                    + FileUpload1.FileName);
                Label1.Text = "File uploaded!";
            }
            catch (Exception ex)
            {
                Label1.Text = "File could not be uploaded.";
            }
        }
        else
        {
            Label1.Text = "Cannot accept files of this type.";
        }
    }
}


Up Next
    Ebook Download
    View all
    Learn
    View all