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

Syntax for private members in ES6 classes

I'm curious to know the most efficient way to declare private members within ES6 classes. In simpler terms, what is the best practice for implementing: function MyClass() { var privateFunction = function() { return 0; }; this.publicFuncti ...

Create an object using a combination of different promises

Creating an object from multiple promise results can be done in a few different ways. One common method is using Promise.all like so: const allPromises = await Promise.all(asyncResult1, asyncResult2); allPromises.then([result1, result2] => { return { ...

Passing a list of objects containing lists in MVC3

Is it possible for me to send an array of objects, each containing arrays, from JavaScript to a MVC action result method? Essentially, I have a KeyValuePair with keys as arrays of strings and I need to return a list of these KeyValuePairs. In my code, I ha ...

javascript highchart image carousel

I am currently working on a visual chart project using the JavaScript library highchart. After setting up my chart with some dummy data, I am looking to incorporate functionality that allows for triggering an image slide based on the chart data. Specific ...

Unintended consequences within computed properties

I'm struggling to eliminate side effects in my code. Can anyone offer some guidance? computed: { sumVegetables(){ this.totalVegetables = 0; for( const vegetable of this.vegetables){ this.totalVegetables ...

What is the process for making an Ajax request in Rails?

I'm attempting to send a variable through jQuery using the POST method, saving it in a controller, and then utilizing that same variable in Rails HTML to query a table. It seems like the variable isn't being passed to the controller. jQuery: v ...

Mastering the Art of Leveraging Conditionals in JavaScript's Find Function

I'm curious about the implementation of an if statement in the JavaScript find function. My objective is to add the class "filtered-out" to the elements in my cars array when their values do not match. cars.map(car => active_filters.find(x => ...

Is there a way to bring in a variable from the front end script?

Is it possible to transfer an array of data from one HTML file to another? If so, how can this be done? Consider the following scenario: First HTML file <script> let tmp = <%- result %>; let a = '' for (const i in tmp){ ...

Utilizing the $.ajax method to navigate to a webpage displaying only the results that correspond to the value in the json data

I'm in the process of creating a single page application that utilizes $.ajax. Here is the JSON data: { "restaurants": [ { "id": 1, "name": "Denny's", "location": "Los Angeles", "cuisine": "American", "image_ ...

A scenario in a Jasmine test where a function is invoked within an if statement

My coding dilemma involves a function: function retrieveNames() { var identifiers = []; var verifyAttribute = function (array, attr, value) { for (var i = 0; i < array.length; i++) { if (array[i][attr] === va ...

Shape with a dark border div

Having some trouble with creating this particular shape using CSS border classes. If anyone can assist in making this black box shape using Jquery, it would be greatly appreciated. Check out the image here. ...

Tips for refreshing a D3.js bubble chart with live JSON data updates

Currently delving into d3 and experimenting with transforming a static bubble chart into a dynamic one that adjusts by removing or adding bubbles based on JSON changes. I am aiming to have the JSON file refreshed every 5 seconds to update the bubble chart ...

Sending a variable to a function in JavaScript (winJs) from a different function

Greetings! Currently, I am developing a Windows 8 app using Java Script. function fetchFromLiveProvider(currentList, globalList,value) { feedburnerUrl = currentList.url, feedUrl = "http://ajax.googleapis.com/ajax/services/feed/load?v=1.0&outpu ...

What is the proper syntax for adding boolean values to the Realtime Database?

Hello, I am trying to store boolean values in a folder using names like "female" so the name is set to either true or false. This way, I can later retrieve a list of users belonging to a specific group. However, I am unsure about how to update these values ...

This error message appears in vue.js: "TypeError: Trying to read an undefined property 'then'."

I am currently working on implementing email verification in my vue.js/express application. I have successfully created the user and sent emails. However, displaying a message like "verification mail sent" is not functioning as expected. The issue arises ...

Tips for navigating to an external website through GraphQL

I am currently utilizing Node.js and Front-end on Next.js. I have a GraphQL server with a GetUrl method that returns a link (for example: ""). My goal is to redirect a client who made a request to that page with a Basic Auth Header. From what I understan ...

Ways to incorporate a loading feature in javascript, jquery, and php as it runs?

I have created a form that, when clicked on, returns a value within the page. Below is my form. When the form is submitted, it takes some time to process. I would like to display a loading message while the code is being executed. Here is my form: <ht ...

Animating background images using a single data attribute

I'm attempting to create a smooth animation between different background images stored in a single data attribute. The goal is for each image to load sequentially, with the first one appearing immediately and the rest following after a 5-second delay. ...

Discover and select an element based on its partial `onclick` attribute value

Can an element be clicked through selenium based on a partial value of an onclick attribute? There are several input elements on the page, and I am interested in selecting one with a specific string. Examples would include: <input name="booksubmit" t ...

Enhance the performance of page loading and implement a consistent spinner feature to ensure smooth transitions for users in Next.js version 13

I am currently working on a project using Next.js 13, and I am encountering issues with slow loading times and an unstable spinner when navigating between pages. Specifically, when transitioning from the home page to the /example page, the experience is n ...