Draaksward
Draaksward

Reputation: 779

Ajax post with a file return

Is there a way to return a dynamically server-side generated file, which was fetched from a ajax post structure?

Writing a small web mvc project, which generates a list of data(the data is generated from a complex aggregation query and cannot be called from id or whatsoever), and come up to the part on which i want to export some selected parts to a file and download it.

How does it work: 1. On the page i select some fields with key data(using JQuery DataTable) 2. Send it to a controller(Spring to be precise) 3. Generate a bytestream and return it as a HTTPResponse with "Content-disposition", "attachment" header.

Thing is that i select the lines and form the needed data using JQuery->Ajax, so the result of the Controller->Post stays inside the javascript part, not giving me a "Save as...".

I'm already thinking of a temporary directory or something, but saving option for the last.

Upvotes: 2

Views: 679

Answers (1)

Haresh Vidja
Haresh Vidja

Reputation: 8496

Unfortunately you can not get file through ajax, but you can achieve it by generate form dynamically and submit it. As per our comment discussion for generate form and submit it you can do something like this.

function autoSubmitForm(method, url, post_data) {
    var element = document.getElementById("virtual_form");
    if(element != null )
    {
        element.parentNode.removeChild(element);
    }
    var form = document.createElement("form");
    form.setAttribute("id", "virtual_form");
    form.setAttribute("style", "display:none;");
    form.method = method;
    form.action = url;   
    for(i in post_data)
    {
         var element=document.createElement("input");
         element.value=post_data[i];
         element.name=i;
         form.appendChild(element); 
    }
    document.body.appendChild(form);
    form.submit();

}

autoSubmitForm('POST','your_url.php',{id:"xyz",other_input:"input value"});

Here {id:"xyz",other_input:"input value"} is object of post data you can define it dynamically pair of field name and value of field. pass it in function.

Upvotes: 1

Related Questions