Saturday, 30 November 2013

How To Upload Multiple 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 multiple file in your application folder.

Aspx Page:-


<div>

        <asp:FileUpload ID="fu_1" runat="server" multiple="true"></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)
        {
            int Total= 0,success= 0,unsuccess= 0;
            HttpFileCollection fileCollection = Request.Files;
            string notuploaded = string.Empty;
            for (int i = 0; i < fileCollection.Count; i++)
            {
                HttpPostedFile uploadfile = fileCollection[i];
                string fileName = Path.GetFileName(uploadfile.FileName);

                if (uploadfile.ContentLength < 5242880)
                {
                    if (CheckFileType(fileName))
                    {
                        string uploadpath = "~/Files/" + fileName;
                        fu_1.SaveAs(MapPath(uploadpath));
                        Total++;
                        success++;
                    }
                    else
                    {
                        Total++;
                        unsuccess++;
                    }
                }
                else
                {
                    Total++;
                    unsuccess++;
                }
            }
            lblmsz.Text = "<span style='color:Green;'>Total Files = " + Total + " Successful Uploads = " + success + "</span><span style='color:Red;'> Unsuccessful Uploads = " + unsuccess + "</span>";
         

        }


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;
            }
        }

Example:-


 1. Five files Selected 1 excel and 4 jpeg files

2.  Jpeg files are uploaded because Excel file allowed.


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

No comments:

Post a Comment