2

The issue is I want to download the response of the backend to the excel file and the response recognized as binary by talend API here is my code

function get_excels(type, id) {
  $.ajax({
      method: "GET",
      url: URL+id+"/"+type+"/excel",
      success: function (result) {
          var blob = new Blob([result], {
              type: "application/json",
          });
          const link = document.createElement("a");
          link.href = URL.createObjectURL(blob);
          console.log(link.href);
          link.download = `excel.xlsx`;
          link.click();
      },
  });
}
<i onclick="get_excels('transactions', 1)" class="fas fa-file-excel"></i>

Here is the talend API response

And here is the result of the GET method

When I download the file, Microsoft excel throws this error picture

I need to know how can I handle the response from the API and download It as an excel file. I will appreciate it If you can help me out.

Niaz Estefaie
  • 567
  • 6
  • 21

1 Answers1

1

There is no need to read the ajax content and then download it, you can let the browser directly download it which will handle both the filename and the extension - this is also more time/memory efficient.

function get_excels(type, id) {
  const a = document.createElement('a')
  a.href = URL+id+"/"+type+"/excel"
  a.download = true // the browser will download the file and name it as the original file name and extension
  document.body.appendChild(a)
  a.click()
  document.body.removeChild(a)
}

ehab
  • 7,162
  • 1
  • 25
  • 30