How to get download file (.xlsx) with axios in Vuejs?

Viewed 392

I am trying to send an .xlsx from the server in Rails 6 (using the 'caxlsx' gem to generate the file) to the client made in Vuejs.

This is my backend controller

  def export_data
    respond_to do |format|
      format.xlsx {render xlsx: 'export_data', filename: "data-people-"+Time.now.strftime("%-d %b %Y")+'.xlsx',
                          disposition: "inline" }
    end
  end

and this is my call from the front

axios
  .get("/people/export_data.xlsx",{params:{
      filter_unit: this.filter_unit,
   }},
   {
      responseType: 'blob',
      headers: { 'Accept': 'application/vnd.ms-excel' }
   }).then((response) => {
      const url = window.URL.createObjectURL(new Blob([response.data]));
      const link = document.createElement('a');
      link.href = url;
      link.setAttribute('download', 'file.xlsx');
      document.body.appendChild(link);
      link.click();
      this.isLoading = false
   });

This generates a download dialog for me but the file I can download is corrupt. On the other hand if I insert the controller path directly in the browser the file is downloaded correctly, so I think the problem is not in the backend unless I am not understanding something.

What am I doing wrong?

0 Answers
Related