Friday, 29 November 2013

How To Upload File in your Application Folder in Asp.Net

How To Upload File in your Application Folder in Asp.net


Here is the code to upload a file in your application folder.

Aspx Page:-

<div>
        <asp:FileUpload ID="fu_1" runat="server"></asp:FileUpload>
        <asp:Button ID="btn_upload" runat="server" Text="Upload" 
            onclick="btn_upload_Click" />
            <br />
            <asp:Label runat="server" ID="lblmsz" Font-Bold="true"></asp:Label>
    </div>

CS Page:-

Name Space Used:-

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.IO;
using System.Drawing;


Upload Button Code:-


protected void btn_upload_Click(object sender, EventArgs e)
        {
            if (fu_1.HasFile)
            {
                if (CheckFileType(fu_1.FileName))
                {
                    string uploadpath = "~/Files/" + fu_1.FileName;
                    fu_1.SaveAs(MapPath(uploadpath));
                    lblmsz.Text = "File uploaded successfully";
                    lblmsz.ForeColor = Color.Green;
                }
                else
                {
                    lblmsz.Text = "Invalid file selected";
                    lblmsz.ForeColor = Color.Red;
                }
            }
            else
            {
                lblmsz.Text = "Please Select a file";
                lblmsz.ForeColor = Color.Red;
            }
        }


Check File Type Code:-


bool CheckFileType(string fileName)

        {

            string ext = Path.GetExtension(fileName);

            switch (ext.ToLower())

            {
                case ".gif":
                    return true;
                case ".png":
                    return true;
                case ".jpg":
                    return true;
                case ".jpeg":
                    return true;
                default:
                    return false;
            }
        }





Don't forget to leave your feedback and comments below..!

No comments:

Post a Comment