Subscribe

Close

Thank you for visiting!

Please consider subscribing to the RSS feed or following me on Twitter.

Ajax File Download That Works!

So you want to download a file and show an Ajax loader until the download is complete? Here's a way to do it:

  1. User clicks the download button and a JavaScript function is called.  In this JS function, a number of things will happen:
    • Show an AJAX loader.
    • Create a cookie.
    • Run a check cookie function.
    • Redirect to the file download (in this case an MVC method that returns the file).
  2. If successful, the MVC method removes the cookie and returns the file. When the cookie is removed, disable the Ajax loader (happens in check cookie function).
  3. Done.

Step 1 - JS call

User clicks our download button and we call this export function. Note: just before we create the timer and cookieName variables.

var timer = null;
var cookieName = 'App_FileExportCookie';
	
var export = function () {
    $('#ajax-loader').show();

    var cookie = $.cookie(cookieName);

    if (cookie === undefined) {
        cookie = $.cookie(cookieName, 0);
    }
    checkCookie();

    window.location = '/FileExport';
}

We show the Ajax loader and then check if a cookie exists (using jQuery Cookie plugin). Finally we redirect to the URL where the actual file generation and download will happen.

Step 2 - Check cookie

In step 1, we called the checkCookie function. This one is really important as it will check and see the status of the file download, through checking our cookie.

var checkCookie = function (doClearTimeout) {

    if (doClearTimeout) {
        clearTimeout(timer);
    }
    else {
        timer = setTimeout(function () {

            var cookie = $.cookie(cookieName);

            if (cookie === undefined) {
                $('#ajax-loader').hide();
	        checkCookie(true);
	    } else {
            checkCookie(false);
	    }
	}, 1500);
    }
}

What will happen here, is we set a timeout where we look for our cookie. We call this function until we can't find the cookie we created in step 1 any more. When the cookie doesn't exist, we hide the AJAX loader and clear the timeout.

Finally, we need a place to remove the cookie. Enter step 3.

Step 3 - file generation and remove cookie

In step 1, we redirected the user to the /FileExport url. In ASP.NET MVC, we will have an ActionResult with that name and here we will generate and return the file, plus remove the cookie we created in the beginning. The final code:

private string _fileCookieName = "App_FileExportCookie";
private const string _excelMimeType =
 "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";

public FileResult FileExport()
{
    ExcelFile excel;
	
    try {
        excel = GenerateExcel();
    }
    catch (Exception ex)
    {
        // handle exceptions
    }
    finally
    {
	// same as in JavaScript cookie name
	var cookieName = _fileCookieName;
	var cookie = Request.Cookies[_fileCookieName];

	if (cookie != null)
	{
    	    cookie.Expires = DateTime.Now.AddDays(-1);
	    Response.SetCookie(cookie);
        }
    }
	
    return File(excel.FilePath, _excelMimeType);
}

This is just some pseudo code for generating an Excel file, the important stuff happens in the finally block. We look for our cookie and remove it once the file is generated. Finally, we return the file in proper Excel format.

That's it!

To the top