0

I am getting some CSV data from an Ajax request. I am trying to use FileSaver.js (https://github.com/eligrey/FileSaver.js/) to enable the end-user directly download this data as a CSV file.

This is the code used in my Ajax request handler.

            jQuery.post(urlPrefix + "/api/ReportData",
                    dataToPost,
                    function (data, status) {

                        var blob = new Blob([data], { type: "text/csv" });
                        var fileName = "";
                        fileName += "Data-Export";
                        fileName += ".csv";
                        saveAs(blob, fileName);

                    });

This code is called from a button click event. Whenever the code executes, a new tab is opened, and the file is saved without a csv extension. In fact, the downloaded file has no extension at all. See the attached screenshot for details. The (7) is due to this being my seventh download.

The actual file that is saved is a valid file. If I manually set its extension to csv, I can use it properly. But I want to know how to use FileSaver to generate appropriate extension, and also download the file without opening a new tab.

enter image description here

What I have already tried

  1. Export to CSV using jQuery and html
Shuaib
  • 697
  • 2
  • 11
  • 43

1 Answers1

0

I found out this link https://code-maven.com/create-and-download-csv-with-javascript where it is possible to create a hidden anchor tag and download the file.

My new code is below

jQuery.post(urlPrefix + "/api/ReportData",
                    dataToPost,
                    function (data, status) {

                        var hiddenElement = document.createElement('a');
                        hiddenElement.href = 'data:text/csv;charset=utf-8,' + encodeURI(data);
                        hiddenElement.target = '_blank';
                        hiddenElement.download = 'Exported-Data.csv';
                        hiddenElement.id = "customTemporaryAnchor";
                        hiddenElement.click();

                        jQuery("#customTemporaryAnchor").remove();

});

When this code is executed, the file downloads with proper extension, and without any popup or new tab.

Shuaib
  • 697
  • 2
  • 11
  • 43