4

Click here to load reader

Multiple File Upload in ASP.net _ EncodeDna

Embed Size (px)

DESCRIPTION

code

Citation preview

Page 1: Multiple File Upload in ASP.net _ EncodeDna

7/7/13 Multiple File Upload in Asp.Net | EncodeDna.com

www.encodedna.com/2013/02/multiple-file-upload-in-aspdotnet.htm 1/4

February 21st, 2013

Multiple File Upload in Asp.Net

Microsoft’s .Net has a come a long way when it comes to uploading various typesof files. With Asp.Net version 2.0, it has introduced the “FileUpload” server sidecontrol for the very first time. This has virtually simplified the file uploadingprocess.

Here in this article we will show you how to upload “Multiple” files using the “FileUpload” control along with the

“HttpFileCollection” class. We will also restrict the number of files to be uploaded at one time, to 10.

Note: Restricting file size has an advantage. It will not put unnecessary burden on the Host server and multiple files

can be efficiently uploaded.

Also we will check for duplicate files while uploading the files to the server, ignoring the files extension. That is,

we will not upload more than 1 file with the same name, irrespective of the file type.

E.g.: If the first file is “1.jpeg” and uploaded, then “1.pdf” will be considered duplicate and will not be uploaded.

The Asp.Net “FileUpload” control is a combination of a “Textbox” and a “Button” control. Together they allow us to

select file(s) to upload at a remote location. Clicking the button will pop up a “Dialog box” or a “Window”, which will

show a list of “Folders” and “Files” in the drive of your local machine. The “Textbox” will show the full path with the

selected file(s) name.

By default the “FileUpload” control will allow the users to select only a “single” file at a time. This is how it looks

when you first add it to the web page.

<asp:FileUpload ID="fileUpload" runat="server" />

To allow the users to select “Multiple” files just add multiple=“true”.

<asp:FileUpload ID="fileUpload" multiple="true" runat="server" />

Finally to upload these files we will use Asp.Net HttpFileCollection class. This class will keep an eye on all the files

upload from client side. There by giving vital information about the file size, type etc. Along with it we will use

“System.IO” namespace, which will allow us to check for duplicate files in a particular Folder or Directory on the

server.

Complete Source (Default.aspx.cs)

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>

<!DOCTYPE html>

<html>

<head id="Head1" runat="server">

<title>Multiple File Upload</title>

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>

<style type="text/css">

#divFile p { font:13px tahoma,arial }

#divFile h3 { font:16px arial,tahoma; font-weight:bold }

</style>

</head>

home asp.net jquery gridview javascript image converter contact us Search

encodedna - asp.net

asp.netSubscribe to Encode Dna articles.

enter your email address Continue

Show the Sum of GridView Column Values inFooter in Asp.Net – C# and Vb.Net

Delete Files in a Folder using JQuery Ajaxand Asp.Net

Pass Multiple Parameters using JQuery Ajaxto an Asp.Net Web Method

Return Multiple Values Using Asp.Net WebService and JQuery Ajax

Insert New Records in Database Table UsingGridView

Like 35 Send

XML to PDF Enginewww.ecrion.com

On the fly XML to PDF conversion,supports Visual Design. Try now!

Report Miner 4.0www.ReportMiner.com

Software that Catalogs Your CrystalReport Files. Free Trial.

$0.01 Web Hosting Promowww.HostGator.com/PennyPromo

Secure Web Hosting, Free Domain. TryOur Award-Winning Service Now!

Automated .NET DeploymentOctopusDeploy.com

Deploy ASP.NET websites and WindowsServices using NuGet

http://www.google.com/url?ct=abg&q=https://www.google.com/adsense/support/bin/request.py%3Fcontact%3Dabg_afc%26url%3Dhttp://www.encodedna.com/2013/02/multiple-file-upload-in-aspdotnet.htm%26gl%3DID%26hl%3Den%26client%3Dca-pub-5222830587664038%26ai0%3DCrKKbcE7YUdnvI4u7igeYvIHABKiB4p4DyKX2xBbAjbcBEAEgwpeeHigEUMvzh8n______wFg6QKgAY7f6_4DyAEBqAMByAPTBKoElgFP0EbycT-MR-FNWCnTsgtyLWERoDBKPgiBvDqQ97FpruJ19LhgvLiUKAbuQ0BGuqgbyIAeMND5exlUNI82_e1HQtvKAkjZMDKVDYpoI7qpWw5BjEvKRtRjIx0rV7zo5o-WE7G3xl3OQCm-EnjSaGHx-KPqr8--SeaJPOj1g1hEeZfN40JOilDfQykNYPeurw0TvTuHNuCIBgGAB9qglAE%26ai1%3DCsRS4cE7YUdnvI4u7igeYvIHABK-l1tkB88Py2gPAjbcBEAIgwpeeHigEUJmN_I0DYOkCoAHT9cr-A8gBAagDAcgD0wSqBJYBT9Am73A_j0fhTVgp07ILci1hEaAwSj4Igbw6kPexaa7idfS4YLy4lCgG7kNARrqoG8iAHjDQ-XsZVDSPNv3tR0LbygJI2TAylQ2KaCO6qVsOQYxLykbUYyMdK1e86OaPlhOxt8ZdzkApvhJ40mhh8fij6q_PvknmiTzoqugyU3mXzeNCTopQ30MpDWD3rq8NE707vivGiAYBgAeVirUB%26ai2%3DCIBaWcE7YUdnvI4u7igeYvIHABJuv290Dg-PZ7n3AjbcBEAMgwpeeHigEUO-F8j1g6QKgAdO4lP8DyAEBqAMByAPTBKoEmQFP0HbAcj-OR-FNWCnTsgtyLWERoDBKPgiBvDqQ97FpruJ19LhgvLiUKAbuQ0BGuqgbyIAeMND5exlUNI82_e1HQtvKAkjZMDKVDYpoI7qpWw5BjEvKRtRjIx0rV7zo5o-WE7G3xl3OQCm-EnjSaGHx-KPqr8--MeWJdOh0yJCwL0HhFkGOf1MftmodlbS-Gg4XHT0HGLPdl46IBgGAB5XHaw%26ai3%3DCCDc7cE7YUdnvI4u7igeYvIHABN_X4fsDt4Sf7WPAjbcBEAQgwpeeHigEUOGgqeb-_____wFg6QKgAdn5t9sDyAEBqQJqw8aUxmquPqgDAcgD0wSqBJcBT9A2mXc_iUfhTVgp07ILci1hEaAwSj4Igbw6kPexaa7idfS4YLy4lCgG7kNARrqoG8iAHjDQ-XsZVDSPNv3tR0LbygJI2TAylQ2KaCO6qVsOQYxLykbUYyMdK1e86OaPlhOxt8ZdzkApvhJ40mhh8fij6q_PvknmiTzoyrd2TnmXzeNCTopQ30MpDWD3rq8NE707jH4HX4gGAYAHj4bIJA&usg=AFQjCNHYn9A3LHSxmwCk29_-jqdBzDhhRw
Page 2: Multiple File Upload in ASP.net _ EncodeDna

7/7/13 Multiple File Upload in Asp.Net | EncodeDna.com

www.encodedna.com/2013/02/multiple-file-upload-in-aspdotnet.htm 2/4

<body>

<form id="form1" runat="server">

<div id="divFile">

<h3>Mulple File Upload in Asp.Net (C#)</h3>

<p><asp:FileUpload ID="fileUpload" multiple="true" runat="server" /></p>

<p><input type="button" id="btUpload" value="Upload Files"

onserverclick="btUpload_Click" runat="server" /></p>

<p><asp:label id="lblFileList" runat="server"></asp:label></p>

<p><asp:Label ID="lblUploadStatus" runat="server"></asp:Label></p>

<p><asp:Label ID="lblFailedStatus" runat="server"></asp:Label></p>

</div>

</form>

</body>

<script>

$('#btUpload').click(function() { if (fileUpload.value.length == 0) { alert('No files selected.'); return false; } });

</script>

</html>

C#

using System;

using System.Collections.Generic;

using System.Linq;

using System.Web;

using System.Web.UI;

using System.Web.UI.WebControls;

using System.IO;

public partial class _Default : System.Web.UI.Page

{

protected void btUpload_Click(object sender, EventArgs e)

{

if (fileUpload.HasFile) // CHECK IF ANY FILE HAS BEEN SELECTED.

{

int iUploadedCnt = 0;

int iFailedCnt = 0;

HttpFileCollection hfc = Request.Files;

lblFileList.Text = "Select <b>" + hfc.Count + "</b> file(s)";

if (hfc.Count <= 10) // 10 FILES RESTRICTION.

{

for (int i = 0; i <= hfc.Count - 1; i++)

{

HttpPostedFile hpf = hfc[i];

if (hpf.ContentLength > 0)

{

if (!File.Exists(Server.MapPath("CopyFiles\\") + Path.GetFileName(hpf.FileName)))

{

DirectoryInfo objDir = new DirectoryInfo(Server.MapPath("CopyFiles\\"));

string sFileName = Path.GetFileName(hpf.FileName);

string sFileExt = Path.GetExtension(hpf.FileName);

// CHECK FOR DUPLICATE FILES.

FileInfo[] objFI = objDir.GetFiles(sFileName.Replace(sFileExt, "") + ".*");

if (objFI.Length > 0)

{

// CHECK IF FILE WITH THE SAME NAME EXISTS (IGNORING THE EXTENTIONS).

foreach (FileInfo file in objFI)

{

string sFileName1 = objFI[0].Name;

string sFileExt1 = Path.GetExtension(objFI[0].Name);

if (sFileName1.Replace(sFileExt1, "") == sFileName.Replace(sFileExt, ""))

{

iFailedCnt += 1; // NOT ALLOWING DUPLICATE.

break;

}

}

}

else

{

// SAVE THE FILE IN A FOLDER.

hpf.SaveAs(Server.MapPath("CopyFiles\\") + Path.GetFileName(hpf.FileName));

iUploadedCnt += 1;

}

}

}

}

lblUploadStatus.Text = "<b>" + iUploadedCnt + "</b> file(s) Uploaded.";

lblFailedStatus.Text = "<b>" + iFailedCnt + "</b> duplicate file(s) could not be uploaded.";

}

else lblUploadStatus.Text = "Max. 10 files allowed.";

Page 3: Multiple File Upload in ASP.net _ EncodeDna

7/7/13 Multiple File Upload in Asp.Net | EncodeDna.com

www.encodedna.com/2013/02/multiple-file-upload-in-aspdotnet.htm 3/4

}

else lblUploadStatus.Text = "No files selected.";

}

}

Vb.Net

Option Explicit On

Imports System.IO

Partial Class _Default

Inherits System.Web.UI.Page

Protected Sub btUpload_ServerClick(ByVal sender As Object, ByVal e As System.EventArgs) _

Handles btUpload.ServerClick

' CHECK IF ANY FILE HAS BEEN SELECTED.

If fileUpload.HasFile Then

Dim iUploadedCnt As Integer = 0

Dim iFailedCnt As Integer = 0

Dim hfc As HttpFileCollection = Request.Files

lblFileList.Text = "Select <b>" & hfc.Count & "</b> file(s)"

If hfc.Count <= 10 Then ' 10 FILES RESTRICTION.

For i As Integer = 0 To hfc.Count - 1

Dim hpf As HttpPostedFile = hfc(i)

If hpf.ContentLength > 0 Then

If Not File.Exists(Server.MapPath("CopyFiles\") & Path.GetFileName(hpf.FileName)) Then

Dim objDir As New DirectoryInfo(Server.MapPath("CopyFiles\"))

Dim objFI As FileInfo() = objDir.GetFiles(Replace(Path.GetFileName(hpf.FileName), _

Path.GetExtension(hpf.FileName), "") & ".*")

If objFI.Length > 0 Then

' CHECK IF FILE WITH SAME NAME EXISTS (IGNORING THE EXTENTIONS).

For Each file As FileInfo In objFI

If Replace(objFI(0).Name, Path.GetExtension(objFI(0).Name), "") = _

Replace(Path.GetFileName(hpf.FileName), Path.GetExtension(hpf.FileName), "") Then

iFailedCnt = iFailedCnt + 1

Exit For

End If

Next

Else

' SAVE THE FILE IN A FOLDER.

hpf.SaveAs(Server.MapPath("CopyFiles\") & Path.GetFileName(hpf.FileName))

iUploadedCnt = iUploadedCnt + 1

End If

End If

End If

Next i

lblUploadStatus.Text = "<b>" & iUploadedCnt & "</b> file(s) Uploaded."

lblFailedStatus.Text = "<b>" & iFailedCnt & "</b> duplicate file(s) could not be uploaded."

Else

lblUploadStatus.Text = "Max. 10 files allowed."

End If

Else

lblUploadStatus.Text = "No files selected."

End If

End Sub

End Class

For single file upload just add the below code in the “Button” click event.

fileUpload.SaveAs(Server.MapPath("CopyFiles\" & fileUpload.FileName))

Note: "CopyFiles\" is the name of the folder at the server, in which thefiles will uploaded.

For any queries, please send us an Email.

ENCODE DNA

This website is an effort to present good, useful articles and

codes for programmers, web developers and beginners.

We at encodedna.com believe that sharing is another way

Categories Follow us via

Image Converter

► Upload PDF ► File Upload ► ASP Net PDF ► JavaScript Upload

asp.net

ASP.NET

JQUERY

MS-EXCEL

SQL SERVER

Facebook

Google+

Page 4: Multiple File Upload in ASP.net _ EncodeDna

7/7/13 Multiple File Upload in Asp.Net | EncodeDna.com

www.encodedna.com/2013/02/multiple-file-upload-in-aspdotnet.htm 4/4

of learning, so we welcome suggestions and thoughts from

the entire developer community.

Read more about us...

Contact Us

GRIDVIEW

CRYSTAL REPORT

JAVASCRIPT

DESKTOP

CSS

A simple tool that enables you to convert images into

other known formats.