MrProgram
MrProgram

Reputation: 5242

Download file using ajax

I have a submit button on a form, when it's pressed the form is submitted and an Excel file is created on the server harddrive (C:/ExcelFiles).

After this has been done (after de form is submitted) I want to download this file using Ajax.

This is what I've done but it's not working:

$(document).on('click', '#saveButton', function () {
$('#saveMessage').empty();
$('#saveMessage').append("<p>Your file has been stored in C:\\ExcelFiles</p>");
var data = $('#fileName').val();
alert(data);
$.ajax({
    type: 'POST',
    url: '/Calculation/Download',
    data: data,
    contentType: 'application/json; charset=utf-8',
    dataType: 'json',
    success: function (returnValue) {
        window.location = '/Calculation/Download?fileName=' + returnValue;
    }
});
});

And my controller action look like this:

    [HttpGet]
    public virtual ActionResult Download(string fileName)
    {
        string fullPath = Path.Combine(Server.MapPath("~/ExcelFiles"), fileName);
        return File(fullPath, "application/vnd.ms-excel", fileName);
    }

Right now nothing happens. What am I doing wrong?

Upvotes: 0

Views: 3351

Answers (1)

leskovar
leskovar

Reputation: 661

You cannot download files from the server by .ajax (due to security reasons). You can however point the browser to that location and download the file. The solution should be something like this:

$(document).on('click', '#saveButton', function () {
    $('#saveMessage').empty();
    $('#saveMessage').append("<p>Your file has been stored in C:\\ExcelFiles</p>");
    var data = $('#fileName').val();
    window.location = '/Calculation/Download?fileName=' + data ;
});

Upvotes: 2

Related Questions