0

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?

MrProgram
  • 5,044
  • 13
  • 58
  • 98
  • Your doing an ajax `POST`, but you action method is restricted to `[HttpGet]` only, have you tried changing the ajax call to `GET` ? – MonkeyCoder Apr 26 '14 at 09:34
  • Check out [this stackoverflow topic](http://stackoverflow.com/questions/4545311/download-a-file-by-jquery-ajax). Same issue and quite a few great answers :) – anno1337 Apr 26 '14 at 09:39

1 Answers1

2

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 ;
});
leskovar
  • 661
  • 3
  • 8