File Upload In ASP.Net 4.5 Using C#
Below is the code to upload file in ASP.Net using C#, the code below allows only image file to be uploaded. Once you are through with the logic you can convert it according to your convenience.
Default.aspx
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default5.aspx.cs" Inherits="Default5" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:FileUpload ID="file" runat="server" /> <br />
<asp:Button ID="btn" runat="server" Text="Upload" OnClick="btn_Click" />
</div>
</form>
</body>
</html>
Default.apsx.cs
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
public partial class Default5 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void btn_Click(object sender, EventArgs e)
{
if (file.HasFile == true)
{
string fname = "";
string fpath = "";
string fext = "";
int flen;
fname = file.FileName;
fpath = Server.MapPath("~/image/");
fext = Path.GetExtension(fname);
fext = fext.ToLower();
flen = file.PostedFile.ContentLength;
if (flen <= 1024)
{
if (fext == ".jpg" || fext == ".bmp")
{
file.SaveAs(fpath + fname);
btn.Text = "Done";
}
else
{
btn.Text = "only image files are allowed";
}
}
else {
btn.Text = "Max File Size Allowed is 1 KB";
}
}
else
{
btn.Text = "please select file to upload";
}
}
}