CODEDIGEST
Home » Articles
Search
 

Technologies
 

Sponsored links
 

CodeDigest Navigation
 

Technology News
No News Feeds available at this time.
 

Community News
No News Feeds available at this time.
 
Upload Multiple Files in ASP.Net Using jQuery in GMAIL style

By Bala Murugan
Posted On Dec 23, 2010
Article Rating:
Average Rating: 5
No of Ratings: 1
No of Comments: 11
Category: ASP.Net
Print this article.

Upload Multiple Files in ASP.Net Using jQuery in GMAIL style


My previous article How to Upload Multiple Files in ASP.Net helped us to create a multiple file uploading system in ASP.Net. The main drawback of that approach is, it requires adding a new file upload control for every extra file we need to upload. Read the article to know more.  Moving forward, we will develop a system where users can select multiple files at a time and upload it one by one or in parallel with a progress bar and cancel button near it, simply like a Gmail style upload system.

Something like below,

Figure 1 - Select multiple files

Ajax like multiple file upload with progress bar using Uploadify jQuery plug-in

Figure 2 - Upload multiple files

Ajax like multiple file upload with progress bar using Uploadify jQuery plug-in

How to do this?

Well, this can be done very easily by using a jQuery file upload plug-in called Uploadify which uses flash for rich Ajax like interface. Basically, when you use this plug-in you will not see page refresh when uploading files to server. The next section will help us to implement the above system in a step by step approach.


Steps

1.      Create a sample web application project in your Visual Studio 2008. In this article, i have used C# as the language of my choice.

2.      Download the latest version of jQuery library from the official site(http://www.jquery.com))and integrate into your project. Read the following Faq’s to integrate jQuery library into your project.

What is jQuery? How to use it in ASP.Net Pages?

How to enable jQuery intellisense in Visual Studio 2008?

How to use jQuery intellisense in an external javascript file?

Create a folder called _scripts in in your project and put the jQuery library inside it.

3.      Next, create a folder in server and provide appropriate permission (Read, Write & Modify)to the ASP.Net service account in order to save the uploaded files. You can also configure this folder in AppSettings of the project so that it can be accessed from code. I have hard coded the path in this article for simplicity.

4.      Download the latest Uploadify plug-in from here. The latest version as of this writing is v2.1.4. Unzip the folder and copy the below files into _scripts directory in your project.

Ø       jquery.uploadify.v2.1.4.min.js

Ø       swfobject.js

Ø       uploadify.css

Ø       uploadify.swf

Ø       cancel.png

5.      The Uploadify plug-in requires an aspx page or an HttpHandler which can be called to upload the selected files in the server. Hence, include a new aspx page or ashx handler in your project ( I have used aspx page called FileUploads.aspx.) This page will have the code to upload the incoming file to the server folder. Refer the code below,

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

{

    protected void Page_Load(object sender, EventArgs e)

    {

        HttpPostedFile uploads = Request.Files["FileData"];

        string file = System.IO.Path.GetFileName(uploads.FileName);

 

        try

        {

            uploads.SaveAs("D:\\UploadedUserFiles\\" + file);         

        }

        catch

        {

            //exception handling code

        }       

    }

}


6.      Now, open your Default.aspx page to design our main interface which the user can use to upload the files which will use jQuery and Uploadify plug-in.  Refer the code below,

Ajax like multiple file upload using Uploadify jQuery plug-in

<head runat="server">

<link href="_scripts/uploadify.css" rel="stylesheet" type="text/css" />

<script type="text/javascript" src="_scripts/jquery-1.4.4.min.js"></script>

<script type="text/javascript" src="_scripts/swfobject.js"></script>

<script type="text/javascript" src="_scripts/jquery.uploadify.v2.1.4.min.js"></script>

    <title>Untitled Page</title>

    <script type="text/javascript">

        $(document).ready(function() {

            $('#fuFiles').uploadify({

                'uploader': '_scripts/uploadify.swf',

                'script': 'FileUploads.aspx',

                'cancelImg': '_scripts/cancel.png',

                'auto': 'true',

                'multi': 'true',

                'buttonText': 'Browse...',

                'queueSizeLimit': 3

            });

        });

</script>

</head>

<body>

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

    <div id="fuFiles"></div>   

    </form>

</body>

</html>

 




If you look at the script above, the Uploadify plug-in will call the server page/handler specified in ‘script’ property to upload the selected file. Also, I have restricted the user to select only 3 files at a time using 'queueSizeLimit' option. There are many other useful properties available in Uploadify plug-in to customize it more. Refer the documentation here.

7.      That’s it! Execute the page and see it in action.

Remember, in the above example I have not done exception handling or validations on the file type (basically file extension), file size, etc as this article concentrates only on multiple file uploading techniques. Keep in my mind that any production code should have these validations in place to prevent any misuse. You can use fileExt to restrict the type of file the user can upload. Refer here to know about the customization options the plug-in offers.

Also, by default ASP.Net has some restriction on file upload size for performance and security benefits. By default, it allows up to 4 MB of files to be uploaded. Refer the below link to know more and change it.


How to increase default File Upload size in ASP.Net ?

You have to change the settings discussed in the above link appropriately for larger files.

Downloads

Download Source

 

 

Conclusion

Uploading multiple files at a stretch is the best way as opposed to uploading file one by one if your application requires uploading files. Thanks to Uploadify plug-in which has made the development easier and simpler with better user experience.

Download the code attached with this article and see it in action.

 

Similar Articles
You can contribute to CodeDiget.Com:
Donate to CodeDigest.com
Article Feedback
Comments
Compablity issue
Working fine Mozilla and chorme,not working in IE 11,As iam using Visual studio 2012
IE 11 Issue
Good article,as I implemented but the Browese button is not visible in IE 11,But I can work with chrome...As i done this sample in Visual studio 2013
How to show files and upload only when user clicks Upload button
The above example works well.

In the given article the files are uploaded as soon as user press upload button.

I would like to ask how to show the files to be uploaded and upload only when user clicks submit button.so that allows user to remove files that are not needed to be uploaded

Http 302 solution
I had the same error when working with asp.net 4.0 later i found that the error was due to deny user. so i comment the line it started working for me. happy using uploadify for dotnet users

<authorization>
<!--<deny users="?"/>-->
</authorization>

my successful code is this
<table>
<tr>
<td colspan="2">
<div style="">
<asp:FileUpload ID="FileUpload1" runat="server" />
</div>
</td>
</tr>
<tr>
<td colspan="2">
<a href="javascript:$('#<%=FileUpload1.ClientID%>').fileUploadStart()">Start Upload</a>&nbsp;
|&nbsp;<a href="javascript:$('#<%=FileUpload1.ClientID%>').fileUploadClearQueue()">Clear</a>
</td>
</tr>
</table>
<div>
</div>
</div>
<script type="text/javascript">
$(window).load(
function () {
var listingid =1000;
var ypcide = 2000;
$("#<%=FileUpload1.ClientID%>").fileUpload({
'uploader': '/js/uploader.swf',
'cancelImg': '/images/cancel.png',
'buttonText': 'Attach Images',
'script': '/handlers/Upload.ashx',
'folder': '/uploads',
'fileDesc': 'Image Files',
'fileExt': '*.jpg;*.jpeg;*.gif;*.png',
'multi': true,
'auto': false,
'scriptData': { 'listingid': listingid, 'rnd': Math.random(), 'ypcid': ypcide, 'syp': '1' },
onError: function (a, b, c, d) {
if (d.status == 404)
alert('Could not find upload script. Use a path relative to: ' + '<?= getcwd() ?>');
else if (d.type === "HTTP")
alert('error ' + d.type + ": " + d.status);
else if (d.type === "File Size")
alert(c.name + ' ' + d.type + ' Limit: ' + Math.round(d.sizeLimit / 1024) + 'KB');
else
alert('error ' + d.type + ": " + d.text);
}
});

}
);
</script>
Http 302 Error
Hi Bala, could u send your code ? How can i check permission on folder ? i'm already set :

<location path="~/admin_ServicesPhotosManager.aspx">
<system.web>
<authorization>
<allow users="*"/>
</authorization>
<httpRuntime executionTimeout="1800"
maxRequestLength="1048576"
useFullyQualifiedRedirectUrl="false"/>
</system.web>
</location>

Http 302 Error
Hi Bala, could u send your code ? How can i check permission on folder ? i'm already set :

<location path="~/admin_ServicesPhotosManager.aspx">
<system.web>
<authorization>
<allow users="*"/>
</authorization>
<httpRuntime executionTimeout="1800"
maxRequestLength="1048576"
useFullyQualifiedRedirectUrl="false"/>
</system.web>
</location>

RE:Error
Checked in IE, FireFox, Chrome. All works fine.
Things you can verify,
1) Check you have flash installed.
2) Create the folder called "UploadedUserFiles" in your D: drive. Else configure it to your choice and change code in FileUpload.aspx.
3) Make sure your asp.net account have permission on the folder
Http 302 Error
Hi, have you run it successfully ? i tried ur post and get http 302 error ? do you have any solution for this issue ?
RE:IE Problem
It works perfectly for me. Please let me know if there is any error to investigate further...
IE Problem
Itsn't worked in internet explorer.
Not working
Hi Bala, I tried to use this project but the default.aspx page seems to be missing something. It comes up blank without a "browse" button as in your screenshot. Thus it can't reach the FileUploads.aspx page. Only the jquery script is there on the default.aspx page.