Upload a file to a Web server in ASP.NET by using Visual C# .NET


Upload a file to a Web server in ASP.NET by using Visual C# .NET


  1. Open the Visual Studio
  2. Click New > Project ASP.NET WebApplication
  1. Name it accordingly


  1. When the Project gets created, right click on it and click on Add > New Item > Web Form
  2. Name the form FileUpload.aspx

  1. Open the FileUpload.aspx the following code

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="FileUpload.aspx.cs" Inherits="ASPFileUpload.FileUpload" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
   <title>FileUpload</title>
</head>
<body>
   <form id="form1" enctype="multipart/form-data" runat="server">
       <p><input type="file" id="File1" name="File1" runat="server" /></p>
       <asp:Button ID="submitbtn" Text="Submit" OnClick="Submit1_ServerClick" runat="server" />
   </form>   
</body>
</html>


  1. Then add the following code i to FileUpload.aspx.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace ASPFileUpload
{
   public partial class FileUpload : System.Web.UI.Page
   {
       protected void Page_Load(object sender, EventArgs e)
       {
        Response.Write("Page Load OK");
       }
       protected void Submit1_ServerClick(object sender, System.EventArgs e)
       {
        Response.Write("<p> The Upload button has been clicked");
       
       
        if ((File1.PostedFile != null) && (File1.PostedFile.ContentLength > 0))
        {
            string fn = System.IO.Path.GetFileName(File1.PostedFile.FileName);
            string SaveLocation = Server.MapPath("Data") + "\\" + fn;
            try
            {
                   File1.PostedFile.SaveAs(SaveLocation);
                Response.Write("<p> The file has been uploaded.");
            }
            catch (Exception ex)
            {
                Response.Write("Error: " + ex.Message);
            }
        }
        else
        {
            Response.Write("Please select a file to upload.");
        }
       }
   }
}


  1. Create  a new folder called “Data” in the root of your project directory. This is where the uploaded files will be stored.
  1. Test by clicking on the “Play button”
  1. Chose the file
  1. Pick the file of your choice




  1. Now hit the submit button
  1. The effect
  1. Now, navigate to the Data folder that you have previously created in the main directory of your project


  1. The file has been uploaded successfully

Comments

Popular posts from this blog

C# - Simple Class Library and how to use it in another project

AWS CLI - INSTALLATION AND CONFIGURATION