Search code examples
ajaxgrailsgroovydownloadcontroller

Call controller in Ajax to download a file in Grails


I'm new to Grails and I'm having troubles for downloading a document generated in my controller.

My jQuery

$("#exportAllSelectedData").click(function() {
   var dataToExport = $("#dataToExport").val();
   jQuery.ajax(
       {type:'POST',
        data:'dataToExport=' + dataToExport ,
        dataType: 'json',
        url:'/myapp/mycontroller/exportPreferences'});;
});

My Controller

def exportPreferences ()
{
    File file = File.createTempFile("export",".xml");
    String dataToWrite = params.dataToExport;
    file.write(dataToWrite);
    response.contentType = "application/octet-stream";
    response.setHeader "Content-disposition", "attachment; filename=${file.name}";
    response.outputStream << file.bytes;
    response.outputStream.flush();
}

I was expecting to download the outputStream with my browser but nothing happened. What am I doing wrong ?

Edit : Thanks Rahul. It worked fine with:

$("#exportAllSelectedData").click(function() {
  var dataToExport = $("#dataToExport").val();
  window.location="<g:createLink controller="mycontroller" 
  action="exportPreferences"/>"+"?dataToExport="+dataToExport
});

Solution

  • You do not required the Ajax to download a file.

    You can simply use window.location to download your file.

    Example:

    $("#exportAllSelectedData").click(function() {
        window.location="<g:createLink controller="mycontroller" action="exportPreferences" />"
    });
    


    If you try with Ajax, you will get(render) file text

    Example:

    $("#exportAllSelectedData").click(function() {
            $.ajax({
                type: "GET",
                url: "<g:createLink controller="demo" action="exportPreferences" />",
                success: function (data) {
                    console.log(data);               
                }
            });
        });
    

    Hope this will helps you.