Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Download file from Ajax (sort of)

I have this ajax call in my GSP:

$.ajax({
    url: '${request.contextPath + '/Ticket/passAll'}',
    type: 'POST',
    data: data,
    success: function() {
        alert("Success");
    }
});

This is code block from my controller action:

response.setHeader("Content-disposition", "attachment; filename=sample.csv")
response.contentType = "application/vnd.ms-excel"

def outs = response.outputStream
def cols = [:]

tickets.each() {
    outs << it.ticketNo + ";" + it.subject
    outs << "\n"
}

outs.flush()
outs.close()

I get tickets list from data that I pass from view via $.Ajax method. Than I format that data as CSV and than I want to export that data as CSV file but nothing happens. The data is send to client but there is no file for download as content-disposition is not well formed. What am I missing? I've tried to do something like:

$.ajax({
    url: '${request.contextPath + '/Ticket/passAll'}',
    type: 'POST',
    data: aoData,
    dataType: 'text',
    success: function(result) {
        var uri = 'data:application/csv;charset=UTF-8,' + encodeURIComponent(result);
        window.open(uri, 'tiketi.csv');
    }
});

and in controller I generate plain string, but that way I get a file without extension which is unacceptable.

How can I achieve this? Thank you.

like image 704
drago Avatar asked Jan 16 '13 15:01

drago


People also ask

Can we download file using Ajax?

Downloading PDF File on Button Click using jQueryInside the DownloadFile JavaScript function, the URL of the File is passed as parameter to the jQuery AJAX function. Inside the jQuery AJAX function, using the XmlHttpRequest (XHR) call, the PDF file is downloaded as Byte Array (Binary Data).

How do I save Ajax file?

preventDefault(); event. stopImmediatePropagation(); var formData = new FormData(this); $. ajax({ url: 'my url', type: 'POST', data: formData, success: function (response) { if (response) { // Do whatever you want to do with response } }, error: function (error) { console.


2 Answers

You dont need to do it via ajax. The page will not redirect for file downloads.

like image 145
James Kleeh Avatar answered Oct 04 '22 03:10

James Kleeh


I guess the url property should be fixed as your quotes are colliding.

Try with:

$.ajax({
    url: "${request.contextPath}/Ticket/passAll",
    type: 'POST',
    data: aoData,
    dataType: 'text',
    success: function(result) {
        var uri = 'data:application/csv;charset=UTF-8,' + encodeURIComponent(result);
        window.open(uri, 'tiketi.csv');
    }
});
like image 26
lucke84 Avatar answered Oct 04 '22 02:10

lucke84