In this article, I will explain how to upload a file to a web server using asp.net C#.
Uploading a file, and save it to a web server through a file upload control with checking file format like jpg, png, gif.
Open visual studio, create a new website, and drag and drop a file upload control, a command button and double click on button paste c# code.
<html xmlns=”http://www.w3.org/1999/xhtml”>
<head runat=”server”>
<title></title>
</head>
<body>
<form id=”form1″ runat=”server”>
<div>
<asp:FileUpload ID=”FileUpload1″runat=”server”/>
<br/>
<asp:Button ID=”Button1″runat=”server”onclick=”Button1_Click”Text=”Upload”/>
<asp:Label ID=”Label1″ runat=”server”></asp:Label>
</div>
</form>
</body>
</html>
// C# Source Code
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
public partialclass _Default: System.Web.UI.Page
{
protected voidPage_Load(object sender, EventArgs e)
{
}
protected voidButton1_Click(object sender, EventArgs e)
{
string[] FileFormat = { “.jpg”, “.gif”, “.png” };
string FileExt =System.IO.Path.GetExtension(FileUpload1.FileName);
// HasFile check to make sure a file selected or not
if (FileUpload1.HasFile)
{
// checking file extesion
if(FileFormat.Contains(FileExt))
{
// save the file to server path
FileUpload1.SaveAs(Server.MapPath(“~/images/” + FileUpload1.FileName));
Label1.Text =“File Uploaded Successfully”;
}
else
{
Label1.Text =“Invalid File Format”;
}
}
}
}