What is the correct method for downloading an Excel file in a Vue.js application?

I am having difficulty downloading an Excel file in xlsx format using my Vue.js application. The Vue.js application sends a post request to the Node.js application which then downloads the Excel file from a remote SFTP server. The backend application is functioning without any issues.

Within the Vue.js application, I have the following code:

axios.post(config.backendHost + '/excel', {
  file_name: fileName
}).then((response) => {
  const url = URL.createObjectURL(new Blob([response.data], {
    type: 'application/vnd.ms-excel'
  }))
  const link = document.createElement('a')
  link.href = url
  link.setAttribute('download', fileName)
  document.body.appendChild(link)
  link.click()
});

Upon browser download of the file, it automatically opens and I encounter an error message that reads:

We found a problem with some content .xlsx. Do you want us to try and recover as much as we can?

Answer №1

Make sure to specify the response type as the third argument in your post request

{
    responseType: 'blob'
}

Your updated code should look something like this

axios.post(config.backendHost + '/excel', {
    file_name: fileName
}, {
    responseType: 'blob'
}).then((response) => {
    const url = URL.createObjectURL(new Blob([response.data], {
        type: 'application/vnd.ms-excel'
    }))
    const link = document.createElement('a')
    link.href = url
    link.setAttribute('download', fileName)
    document.body.appendChild(link)
    link.click()
});

Alternatively, you can utilize FileSaver.js library for saving your file

import FileSaver from 'file-saver'

axios.post(config.backendHost + '/excel', {
    file_name: fileName
}, {
    responseType: 'blob'
}).then((response) => {

    // response.data is a blob type
    FileSaver.saveAs(response.data, fileName);
});

Answer №2

Successfully executed my code:

  axios.get(`/api/v1/companies/${companyId}/export`, {
    responseType: 'blob',
  }).then((response) => {
    const fileUrl = URL.createObjectURL(new Blob([response.data]))
    const downloadLink = document.createElement('a')
    downloadLink.href = fileUrl
    downloadLink.setAttribute(
      'download',
      `${companyId}-${new Date().toLocaleDateString()}.xlsx`
    )
    document.body.appendChild(downloadLink)
    downloadLink.click()
  })

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Tips to center a circular progress bar in Material UI

Does anyone know how to properly center-align a circular progress bar in a login form using material UI? I'm having trouble with it not being positioned correctly: screenshot {isLoading && <CircularProgress />} {user?.ema ...

Leveraging useContext to alter the state of a React component

import { createContext, useState } from "react"; import React from "react"; import axios from "axios"; import { useContext } from "react"; import { useState } from "react"; import PermIdentityOutlinedIcon f ...

Is there a way to determine the app bar height within a React Material UI application?

I'm trying to create a full-screen image for the opening of my website using React and Material UI. Here's a snippet of my JSX code with the default Material UI theme: <AppBar> //code in between </AppBar> <Container sx={{margin: ...

Trigger the reactive helper again when there is a change in the $scope

I am working with a reactive data source in Angular-Meteor and I want to find a method to trigger the reactive function to run again after modifying another $scope value. Specifically, I aim to change the sorting order based on $scope.model.sort: angular. ...

Troublesome code with Ajax, Jquery, and PHP is causing issues

I've been trying to send an array from php to js using ajax, but for some reason it's not working no matter what I try. I'm convinced it must be a simple fix, but I seem to have exhausted all my options. <!doctype html> <html lang= ...

Threejs: Illuminating the spotlight with visibility

For my current project, I am attempting to create a visible spotlight similar to the one used by Batman. I want that cone of light that pierces through the night sky. Unfortunately, I do not have any experience with graphics or 3D design, so I am strugglin ...

What is the best way to rotate a cube when it is clicked on?

My current project involves rotating a cube by clicking on buttons either on the cube itself or floating next to it. At the moment, I have them floating for easier testing purposes, but placing them directly on the cube is not an issue. The main issue I&a ...

What is the best way to convert a document.getElementById(id) element into a jQuery object?

It's surprising that no one has asked this question before: When I create elements using the following code: document.getElementById(id).innerHTML = (a string with id's in it); for example. I want to use jQuery to update the CSS of these dynam ...

Tips for toggling the visibility of a <div> element using PHP code inside

I'm having trouble with a dropdown list that is supposed to show/hide some divs containing PHP files. However, when I try to toggle the visibility of the divs using the dropdown list, it doesn't seem to work as expected. Can anyone help me figure ...

Error message in Vuejs: The injection "Symbol()" could not be found

I encountered an issue while using confirmdialog in primevue. The error message I received is: [Vue warn]: injection "Symbol()" not found I am unsure of the cause of this error and how to resolve it. Any assistance would be greatly appreciated ...

The $timeout function in AngularJS seems to be malfunctioning

I'm attempting to add a delayed effect to my view. After a button is clicked, a message is displayed, but I want it to disappear after 2000ms. I have tried implementing a $timeout function based on recommendations I found, but it doesn't seem to ...

Converting a PHP string into a JSON array

Currently, I am working on making a cURL request and receiving a response that is in the following format when using var_dump: string(595) "{"user_id":1,"currency":"eur","purchase_packs":{"1":{"amount":500,"allowed_payment_methods":["ideal","paypal","visa ...

Having trouble generating a readable output bundle due to the following error message: "The entry module cannot be found: Error: Unable to resolve './src/index.js'"

I'm currently working with Webpack version 6.14.8 within an Asp.net Core Razor Pages project in Visual Studio 2019. My objective is to generate a readable output file, and here's the directory structure I've set up: |-->wwwroot -----> ...

What could be causing the page to refresh every time a post or update is made using a mock REST API with JSON

I have been using Json-Server to mock API requests, but I'm facing an issue where the page reloads every time I fetch or update a post. I've tried searching for a solution, but haven't found one yet. Interestingly, even though I followed a ...

Issue with horizontal scrolling in ng-scrollbars occurs when scrolling from right to left

We are currently developing a single page application that supports two languages, one being right to left and the other left to right. For scrolling functionality, we have implemented ng-scrollbars, an Angularjs wrapper for the malihu-custom-scrollbar-pl ...

Color schemes for items in the Windows store app

I'm having trouble changing the background color of an item in my split application. I've tried using CSS, but nothing seems to work. Here is the template for the item (default style): <div class="itemtemplate" data-win-control="WinJS.Bindin ...

Is it possible to continuously update a Google line chart by programmatically adding rows at specific intervals using an AJAX call

Is there a way to dynamically add rows to the Google line chart each time data is retrieved via an AJAX call at set intervals? This is the existing code: google.charts.load('current', {'packages':['line']}); google.charts. ...

Angular UI-Grid encountering difficulties in rendering secure HTML content

I'm having trouble displaying server-generated HTML in UI-Grid. Specifically, I want to show HTML content in my column header tooltips, but no matter what I try, the HTML is always encoded. Here's an example to illustrate the issue: var app = an ...

What is the best way to set a value in PHP that can be utilized as flight plan coordinates on a Google Map within my script?

I am looking to dynamically update the content of my div with id "map" in response to button clicks, where the flight plan coordinates are changing. Currently, I have attempted to achieve this by assigning PHP output to a JavaScript variable as shown below ...

create a custom function to trigger when a new item is added to a Vuejs data property

Currently, I have a Vuejs application that is relatively simple as I am still in the learning process of Vuejs. My goal is to trigger another function whenever I add or delete from a specific data property. Here is an example code snippet: data: { prici ...