user
user

Reputation: 427

How to download excel using ajax call?

I returned my excel file from spring controllr. but the file is not converting.

Controller :--

Workbook wb = services.downloadExcel(id);
response.setHeader("Content-disposition", "attachment; 
filename=test.xls");
wb.write(response.getOutputStream());
response.flushBuffer();
return wb;

Ajax :--

$.ajax({
    type: "GET",
    url: "/screener/" + projectId,
    success: function (result) {
        console.log(result)
        alert("sfa");
        var blob = new Blob([result], { type: 'application/vnd.ms- 
        excel' });
        var downloadUrl = URL.createObjectURL(blob);
        var a = document.createElement("a");
        a.href = downloadUrl;
        a.download = "downloadFile.xls";
        document.body.appendChild(a);
        a.click();
    }
});

Upvotes: 1

Views: 9753

Answers (1)

Musa
Musa

Reputation: 97672

The method you're using will only work for plain text files, xls is not plain text so you need to retrieve it as binary data.

If you're using jQuery 3+ you can set the responseType of the request to 'blob' and use that blob to create your blob url for download.

jQuery 3+

$.ajax({
    type: "GET",
    url: "/screener/" + projectId,
    xhrFields:{
        responseType: 'blob'
    },
    success: function (result) {
        console.log(result)
        alert("sfa");
        var blob = result;
        var downloadUrl = URL.createObjectURL(blob);
        var a = document.createElement("a");
        a.href = downloadUrl;
        a.download = "downloadFile.xls";
        document.body.appendChild(a);
        a.click();
    }
});

Upvotes: 6

Related Questions