Categorized | ASP.NET

Ajax file upload using jQuery, ASP.NET & C#

This plugin allows users to easily upload multiple files without refreshing the page.

 

Ajax file upload plugin allows users to easily upload multiple files without refreshing the page. In addition, you can use any element to show file selection window.

Demo

View an usage examples with various options. This is a PHP version,

Download

Latest version – 0.6 (8 December 2008) Fixed bug in the "disable" method. Full (7KB) Minified (3KB)  

How to use?

Dependencies

Plugin requires jQuery 1.2 or above.

Creating ASPX Page


 

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

<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
    <title>Demo Page</title>
    <script type="text/javascript" src="Scripts/jquery-1.2.6.min.js"></script>
    <script type="text/javascript" src="Scripts/jquery.ajax_upload.0.6.min.js"></script>
<script type="text/javascript">/*<![CDATA[*/
$(document).ready(function(){
	var button = $('#button1'), interval;
	$.ajax_upload(button,{
		action: 'FileHandler.ashx',
		name: 'myfile',
		onSubmit : function(file, ext){
			// change button text, when user selects file
			button.text('Uploading');

			// If you want to allow uploading only 1 file at time,
			// you can disable upload button
			this.disable();

			// Uploding -> Uploading. -> Uploading...
			interval = window.setInterval(function(){
				var text = button.text();
				if (button.text().length < 13){
					button.text(button.text() + '.');
				} else {
					button.text('Uploading');
				}
			}, 200);
		},
		onComplete: function(file, response){
			button.text('Upload');

			// Although plugins emulates hover effect automatically,
			// it doens't work when button is disabled
			button.removeClass('hover');

			window.clearInterval(interval);

			// enable upload button
			this.enable();

			// add file to the list
			$('<li></li>').appendTo('#example1 .files').text(file);
		}
	});

});/*]]>*/</script>

</head>
<body>
    <form id="form1" runat="server">
<ul>
	<li id="example1" class="example">
		<p>You can style button as you want</p>
		<div class="wrapper">
			<div id="button1" class="button">Upload</div>
		</div>
		<p>Uploaded files:</p>
		<ol class="files"></ol>
	</li>
</ul>
    </form>
</body>
</html>

Server Side Code

If you look at javascript, I’m posting to HttpHandler called "FileHandler.ashx". Here is the code


 

using System;
using System.Web;
using System.IO;

public class FileHandler : IHttpHandler
{

    public void ProcessRequest(HttpContext context)
    {
        string strResponse = "error";
        try
        {

            string strFileName = Path.GetFileName(context.Request.Files[0].FileName);
            string strExtension = Path.GetExtension(context.Request.Files[0].FileName).ToLower();
            string strSaveLocation = context.Server.MapPath("Upload") + "\\" + strFileName;
            context.Request.Files[0].SaveAs(strSaveLocation);
            strResponse = "success";
        }
        catch
        {

        }

        context.Response.ContentType = "text/plain";
        context.Response.Write(strResponse);
    }

    public bool IsReusable
    {
        get
        {
            return false;
        }
    }

}

Popularity: 100% [?]

  • Share/Bookmark

43 Responses to “Ajax file upload using jQuery, ASP.NET & C#”

  1. Amin says:

    Hi

    I am trying use above code but its giving me error saying “Object does not support this property”

    What may be the Problem ?

    Regards
    Amin

  2. admin says:

    Amin,
    Are you using master page ? Based on the error message, it seems to be a client side error.

    Thanks
    Osman

  3. Amin says:

    Hi Osman

    Yes , I am using MasterPage and also m using ASP.NET MVC

    putting datatype as json and trying action UploadFlie which is returning jsonresult instead of FileHandler.ashx,

    I tried with FileHandler.ashx as well
    But still it is giving the above error

    Regards
    Amin

  4. admin says:

    Amin,
    Did you get the sample working project i sent you ?
    I have to look at your aspx and .js file before I can say anything about it.

    Thanks

  5. Amin says:

    Thanks a lot for a demo project

    I have sent you the Asp.net MVC application which giving me “Access denied Error” now in jquery.js I have given asp,net permission to the folder as well

    Can you plz look into it

    Regards
    Amin

  6. admin says:

    Amin,
    The sample I sent you works perfectly fine on couple of machine. I’m sure there has to be some kind of permission issues. Try changing the application folder path and give the asp.net process full access and see if it works.

    I got your MVC sample app and I will look at it

    Thanks

  7. admin says:

    Amin,
    I Looked at your mvc app. The reason you were getting “Access denied..” was because of your javascript in aspx page.

    This is how it is in your script


    $(document).ready(function() {
    /* example 1 */
    var button = $('#button1'), interval;
    $.ajax_upload(button, {
    action: '/Work/UploadFile',
    name: 'myfile',
    dataType: 'json',
    .........

    There is no controller route ” /Work/UploadFile ” in your application. It should be like :


    $(document).ready(function() {
    /* example 1 */
    var button = $('#button1'), interval;
    $.ajax_upload(button, {
    action: '/Home/UploadFile',
    name: 'myfile',

    And another problem is in HomeController

    Inside UploadFile method, it should be
    HttpPostedFileBase file = Request.Files["myfile"];

    “myFile” is name of file in your script.

    After you fix this, you should be able to run it.

    Thanks

  8. Andres says:

    Hi Osman!, I also get the error “Object doesn’t support this property or method”, I just copied & pasted the thos published on your site.
    Could you please help me??
    If I cant make this sample work I´d put it on my intranet where I´m using masterpages.
    Thanks!
    Andres.

  9. admin says:

    Hi Andres,

    If you post your code then i can look at what’s going on.

    Thanks

  10. Andres says:

    Hi Osman, thanks for your reply.
    The code is the same published on this page.
    An aspx file and an ashx file.
    The js included are jquery-1.3.1.min.js and jquery.ajax_upload.1.0.js
    If you wish, I can send the project by email.
    Thanks again!

  11. Will says:

    Hi,
    I have a similar example like the one you showed above…I have two .js file that I want to use in my .aspx page…I have included all the functions in the .js file…so What I need is to just activate the .js file in the .aspx page onmouseOver using only the ID of the div…Hope you will be able to help

    Thanx in advance

  12. Justin says:

    How do you allow the user to select multiple files at once in the selection window? RIght now you can only select one.

  13. Pablo says:

    I am facing the same error message “Access is denied” when trying to upload videos (avi or mpg) and just in Internet Explorer.
    But I made some tests and it works fine if the data type is jpg or png, but when I chango to avi or mpg it throw the error Access is denied.
    Do you know why? Have you had this same issue before?

    Thanks!
    Pablo

  14. admin says:

    Justin,
    You can select one file at a time

  15. admin says:

    Pablo
    Try to change the Httpruntime packet size, may be your video file is too long which is not allowed by Httpruntime.
    Either test with small clip or change the Httpruntime in web.confing like

  16. ankit_sam says:

    Can i know, from where does it calls the “File browsing dialog”? because i dnt see it in .aspx page.

  17. admin says:

    It’s in the jQuery plugin.

  18. ankit_sam says:

    As this is a Ajax file upload,
    When i select the file to upload,
    it gets uploaded smoothly.

    But it also starts the progress bar of IE and progress bar gets completed after few seconds.

    So what is reason it invokes the progress bar, how can i eliminate it??

  19. admin says:

    Well, the jQuery plugin uses hidden iframe to use file upload and that is why IE shows it’s progress bar on the status bar.
    I have to see how can we avoid it.

    lame solution : hide the status bar ;)

  20. ankit_sam says:

    Hi,

    Currently, this Ajax upload overwrites the existing file, i want something like, if file exists then rename to random name and upload.

    So, Is there any way server side ‘FileHandler.ashx’ can also return the modified file name?

  21. ankit_sam says:

    Hi,
    I got the solution of returning the modified file name from server.

    First of all,

    [code]

    var response = iframe.contents().find('body').html();

    if (response == 'success'){
    settings.onSuccess.call(self, file);
    } else {
    settings.onError.call(self, file, response);
    }

    [/code]

    is wrong.

    iframe.contents().find(‘body’).html();

    returns

    sucess

    hence it should be

    iframe.contents().find(‘body’).text();

    otherwise, if condition will never met and “settings.onSuccess” function will never be called.

    Here is the solution,

    In FileHandler.ashx,

    context.Response.Write(strResponse + “|” + strFileName);

    then in JQuery Plugin,

    var tempResponse = response.split(“|”);
    if (tempResponse[0] == ‘success’){
    //
    else
    //

    settings.onComplete.call(self, tempResponse[1], response);

    Cheers,
    Thanks

  22. ankit_sam says:

    LoL,

    iframe.contents().find(’body’).html();

    returns

    Success

  23. ankit_sam says:

    LoL Again,

    I meant it returns “Success” with PRE tags.

    I m done.

  24. Diego says:

    HI,
    I tested the same example is in this page, and in FireFox give me the following error.
    “$.ajax_upload is not a function”
    I am missing something?

    Thanks
    Diego

  25. ajay verma says:

    hi i want to integrate this multiple uploader in my asp.net website please tell me how can we do that or can u please send me the full jquery and code

    i am very new to .net and jquerry

    thanx
    Ajay verma

  26. Muhammad Saqib says:

    [code]
    var response = iframe.contents().find('body').html();
    if (response == 'success'){
    settings.onSuccess.call(self, file);
    } else {
    settings.onError.call(self, file, response);
    }
    [/code]

    Can you tell me where to place this code.
    a quick reply will be appreciated. Thanks.

  27. Carlos says:

    Can’t download your jquery.ajax file, is it because of not being registered?

    Tried registering but seems to be unavailable.

    Your help is greatly appreciated!!

  28. admin says:

    Here is the link from the author of the plugin
    http://valums.com/ajax-upload/

  29. I was just thinking about Ajax file upload using jQuery, ASP.NET & C# and you’ve really helped out. Thanks!

  30. anamika says:

    hi!, i write the same code but got this error when i run this.
    “Microsoft JScript runtime error: Object doesn’t support this property or method”.i m not using master page just doing it in aspx page.plz help me where im doing mistake.

  31. admin says:

    I think it’s because of wrong version of jQuery. Get the latest version of jQuery plugin from the original author of the plugin
    http://valums.com/ajax-upload/

  32. Lee says:

    I’m having the same problem as anamika.
    Copied the code from this page, but get the same error.

    Using latest JQuery version, and latest version of the Plugin from the author’s site as you suggest.

    Please help.

  33. admin says:

    Lee,

    If the error you are getting is thrown in jQuery, then it is for sure the version problem.

  34. Ahmad says:

    This is a great example of AJAX file upload. I have tested it with different browsers. It works perfect in all of them except Safari for windows. In Safari it uploads image but ‘Uploading…’ text does not revert back to ‘Upload’. Button also remains disabled.

    Execution never reaches to ‘onComplete: function(file, response) {‘
    state.

    Could you please look in to this and let me know what can be the problem?

    Best regards,
    Ahmad.

  35. hassan says:

    Hi,

    I am also getting the Access Denied problem when using this script in an MVC application. We have checked and double re-checked everything and made the action=controller/action and still the problem exists. Is there any fix to this issue? Have you tested it in an MVC application

    Thanks in advance

  36. admin says:

    Ahmad,
    I didn’t test with Safari. So, I dunno what’s going on. Please follow-up with this question to original author of this jquery plugin.
    I Just showed to use this plugin in asp.net applications.

    Thanks
    Osman

  37. admin says:

    Hassan,
    I didn’t test with MVC application either.

    Thanks

  38. hassan says:

    Hi again,

    Is there any chance you could test it in an MVC application and may be find a solution?

    Many Thanks

  39. This is a very helpful post, i hope this really helps me to complete my project.

  40. suresh says:

    Hi,

    Could u please explain me how to cancel the File Upload while its getting uploaded.For Example if i have a huge file and when i am trying to upload it,i want to cancel the upload half its way and do some other operation.currently when a request is cancelled ,until it serves the current request it wont go for the next request.so the status bar still shows as progressing.I want canncelling of file upload as the way it happens in gmail.

  41. admin says:

    You may want to see FileUpload control in AjaxControlToolKit

  42. suresh says:

    No in that upload control of ajax control tool kit there is no option for cancelling the file upload.I have seen this option of cancellling file upload in one of the jquery file upload plugin fileuploader.js.

Trackbacks/Pingbacks


Leave a Reply

  • Popular
  • Latest
  • Comments
  • Tags
  • Subscribe

Videos

Calendar

September 2010
M T W T F S S
« Apr    
 12345
6789101112
13141516171819
20212223242526
27282930  

Follow Us