Using Axios in Vuejs to prompt a file download dialog

I am currently working on figuring out how to trigger a file download dialog box after receiving an Ajax request from the Flask server using Axios.

Here is my current client-side code snippet:

<script>
export default {
...
  exportCSV: function() {
    axios.post('/exportdata',
      {
        data: this.data,
      },
      {
        headers: {
          'Content-Type': ' text/html; charset=utf-8'
        }
      }
    )
    .then((response) => {
        var headers = response.headers
        var blob = new Blob([response.data], {type: headers['content-type']})
        var link = document.createElement('a')
        link.href = window.URL.createObjectURL(blob)
        link.download = 'Filename'
        link.click()
    })
    .catch(e => {
      console.log('Error')
    })
  }
}

For my server-side code, I have implemented the following:

return Response(
    json.dumps({'json_data': my_data}, cls=MyEncoder),
    status=200,
    headers = {
        "Content-Disposition": "attachment; filename={0}".format(filename),
    }
mimetype="application/csv")

Although I receive a successful response from the server with valid header data, unfortunately, I am unable to open the file download dialog box. Any suggestions or guidance would be greatly appreciated. Thank you!

Answer №1

To successfully download the file, ensure you include the responseType attribute in your Axios GET request.

axios(url: 'http://localhost:5000/exportdata',
     method: 'GET',
     responseType: 'blob', // make sure to add this line
      }
    )
    .then((response) => {
        const blob = new Blob([response.data])
        const link = document.createElement('a')
        link.href = URL.createObjectURL(blob)
        link.download = 'file.txt'
        link.click()
        URL.revokeObjectURL(link.href) // important for Firefox browser
    })

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

Methods for organizing an array of objects by a specific key in JavaScript, but in the case of duplicate values, the objects can be sorted by a different

I'm struggling to sort an array of objects by two different keys. I need to first sort the array by price, and if there are multiple items with the same price, they should then be sorted by time. Here's what my array looks like: var myArr = [ {&q ...

Sharing application state between different routes in React Router v4 can be achieved by using methods such

I'm seeking solutions to address the following challenge: Without utilizing any state management library, I solely rely on React. The primary application state is contained within the <MyFoodApp/> component, which includes an array of restaura ...

A step-by-step guide on converting JSON data from JavaScript to C# variables

Hey there! I have a JavaScript snippet where I am sending an array to my C# file in JSON format. var r=['maths','computer','physics'] $.post("Global.aspx", { opt: "postpost", post: w.val(),tags:JSON.stringify(r) }, function ...

Positioning the comments box on Facebook platform allows users to

Need assistance, I recently integrated the Facebook comments box into my Arabic website, but I am facing an issue where the position of the box keeps moving to the left. Here is an example of my website: Could someone please suggest a solution to fix the ...

Determine image size (pre-upload)

One of the requirements for a project I am working on is to verify the dimensions (width and height) of images before uploading them. I have outlined 3 key checkpoints: 1. If the dimensions are less than 600 X 600 pixels, the upload should be rejected. ...

What is the best way to create a dropdown menu that smoothly slides in from the bottom of the screen?

Is it possible to create dropdown menus in the navigation bar that slide in from the bottom with a smooth transition effect, similar to this example: Although I am working on building my own template, so my code may differ from the original theme. Here is ...

Creating a unique Vue.js modal window for every individual product

Currently, I am in the process of creating a small online store using Vue.js. Within this store, I have a variety of products each with unique names and prices. In order to provide more information about each product, I have included a "Details" button. M ...

Why does parsing the GET response fail intermittently with Jquery, ajax, and JSON?

Currently, I am encountering an issue with ajax calls using jQuery where the response being returned is a JSON array. In certain scenarios, everything works perfectly fine. However, in other cases specifically in browsers like Firefox and IE11, there seems ...

The design template is failing to be implemented on my personal server utilizing node.js

I've encountered an issue while developing the signup page on my local server using Bootstrap 4. The CSS is not getting applied properly when I run it locally, although it displays correctly in the browser. Can someone explain why this is happening? ...

What advantages does mapState offer compared to mapGetters when working with Vuex?

While evaluating the company code, I came across a Vue component with computed properties structured like this: computed: { ...mapState('settings', { site: state => state.general.site }), ...mapGetters('settings', ...

Trouble with window.location functionality following an AJAX request

After a successful response from an AJAX request, the window.location method is not working as expected. However, when I debug step by step in Firefox, the window.location works fine. function login(){ var jason ={"usuario":document.getElementById("inp ...

Experiencing a challenge with Express and PassportJs when using the Google OAuth2.0 strategy as it's not providing the

Currently, I am in the process of configuring an authentication route for our application. Unfortunately, I am facing a challenge with the Google oAuth 2.0 strategy for PassportJs as it does not provide me with a req.user object when using sequelize. Below ...

Achieving a seamless process of sending two consecutive axios requests in React/Redux without clutter

I am in a situation where I need to send a post request using axios to update a list, followed by a get request to fetch the updated list. After implementing these operations with the code axios(postOptions) and then axios(getOptions), I found that some r ...

Implementing Ajax Js to search within a specific div - reducing text overload on the page

Our e-shop on Prestashop requires an Ajax search feature to find compatible batteries and adapters on the page. Here is the code I have created: https://jsfiddle.net/fgfjo2n9/ I am facing two issues: • 1st I want the output to only display the heading ...

What steps should I take to incorporate Bootstrap's JavaScript into Vue (Gridsome)?

Check out my website: The site is built with Gridsome, a static site generator for Vue. If you navigate to the mobile version and try to open the Bootstrap Hamburger menu, it doesn't work as expected. I've followed the instructions in Gridsome ...

The Jenkins build on a specific branch is encountering issues with path exporting, causing it to fail

I have a set of files related to a new feature that I am trying to deploy through Jenkins. I have successfully deployed other branches in the past, but I am encountering difficulties with a specific branch. I believe the problem may be related to the use ...

Reorganizing JSON structures by incorporating unique identifiers into nested elements

I am working on restructuring an incoming JSON object to utilize in a React component. The JSON data that I'm receiving is stored in jsonData. This is the current structure of my code: const jsonData = { "Jonas": { "position": "CTO", "em ...

Error: Attempting to access property 'PRM_ServerError' on an undefined object is not permitted

After deploying my code to the QA server for testing, I discovered that my image button was not triggering an event. This issue did not occur on the development server. To investigate further, I compared the console output between my local environment and ...

Steps for transferring JSON data from the controller to JavaScript

Within my cluster Table, there is a column called description which stores cluster coordinates in JSON format. I want to draw multiple cluster polygons on Google Maps using these coordinates. id | description ...

Trouble arises when managing click events within the Material UI Menu component

I've implemented the Menu Component from Material UI as shown below - <Menu open={open} id={id} onClose={handleClose} onClick={handleClick} anchorEl={anchorEl} transformOrigin={{ horizontal: transformOriginRight, vertical: t ...