Home Call controller in Ajax to download a file in Grails
Reply: 0

Call controller in Ajax to download a file in Grails

user1265
1#
user1265 Published in April 21, 2018, 3:09 pm

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
});
You need to login account before you can post.

About| Privacy statement| Terms of Service| Advertising| Contact us| Help| Sitemap|
Processed in 0.298676 second(s) , Gzip On .

© 2016 Powered by mzan.com design MATCHINFO