In this short article, We are going to learn how to upload a File using File Upload Control in ASP.NET. Apart from uploading files, we will be applying File Type restrictions to user, so he can not upload malicious files in server.
ASPX Code for File Upload Control
Let’s create a simple design in a ASP.NET Web Form. We Placed a File Upload Control and a button to Click.
<asp:fileupload id="FileUpload1" runat="server">
<asp:button id="BtnUpload" runat="server" text="Upload File" onclick="BtnUpload_Click">
</asp:button></asp:fileupload>
Back-end Code
Now BtnUpload_Click event in .cs page.
We are going to Upload only Picture (.JPG file or .BMP file).
protected void BtnUpload_Click(object sender, EventArgs e)
{
string sSiteFolder = "ResumeFolder";
string sRealPath = Server.MapPath(sSiteFolder);
if (!Directory.Exists(sRealPath))
Directory.CreateDirectory(sRealPath);
string CompletePath = sRealPath + FileUpload1.FileName;
string FileExt = CompletePath.Substring(CompletePath.IndexOf("."));
switch (FileExt)
{
case ".jpg":
FileUpload1.SaveAs(sRealPath + FileUpload1.FileName);
break;
case ".JPG":
FileUpload1.SaveAs(sRealPath + FileUpload1.FileName);
break;
case ".bmp":
FileUpload1.SaveAs(sRealPath + FileUpload1.FileName);
break;
case ".BMP":
FileUpload1.SaveAs(sRealPath + FileUpload1.FileName);
break;
}
}
Enjoy…
John Bhatt