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

Resolving TypeError: matchesSelector method is not recognized within React component

I am currently integrating masonry-layout from the official website to create a masonry grid within my component. However, I encountered an issue where clicking on a rendered element triggers the error message TypeError: matchesSelector is not a function. ...

Combining data from multiple API calls in a for loop with AngularJS

I'm working with an API that contains pages from 1 to 10 and my goal is to cycle through these page numbers to make the necessary API calls. app.factory('companies', ['$http', function($http) { var i; for (i = 1; i < 11 ...

Change the state within the click event handler

One issue I'm facing is dealing with 2 submit buttons in my react form. To differentiate between the two buttons, I need to extract the `id` of the one that was clicked using the `onClick` function. Currently, when trying to set the state with this ` ...

Tips for managing the number of items returned in a dataProvider using AS3

*Hey there! I'm looking to only display 100 items in a list component from a dataProvider, even if it contains more than 500 or even 1000 items. Specifically, I want the first 100 items with cameras on to be included, and then fill the rest to reach a ...

Having trouble populating dropdown using Ajax in CodeIgniter framework

This link contains a filter on the left side. I have been attempting to utilize ajax to retrieve the city based on the state. However, when the ajax is triggered, the entire query changes. SELECT * FROM (`ri_ad_post`) WHERE `state_slug` = 'west-beng ...

Exploring the Ref feature in Vue's Composition API

How do I correctly type my Ref firstName as a string? There are two errors highlighted, one in the template - {{ firstName }}, and the other in the script - const firstName = ref('') as String. I believe the issue lies in the typing, as I assume ...

Determine the status of all jqXHR requests within an array to confirm completion

My goal is to execute a block of code once all the jqXHR elements in an array have completed, whether they have succeeded or failed. For the full code, you can check it out here: http://jsfiddle.net/Lkjcrdtz/4/ Essentially, I am anticipating the use of t ...

Is it possible to determine if a selected date falls within the current week using JavaScript?

Currently facing an issue with JavaScript. I have multiple dates retrieved from a database, and I need to extract the date that falls within the current week. ...

Generating dynamic strings for identifiers in JSX

Can you help me figure out how to dynamically create IDs like this? <div id="track_1"></div> <div id="track_2"></div> I tried assigning the IDs from the parent component like this: export default function Compon ...

Encountering an issue while attempting to iterate through JSON response

After receiving a JSON response from the server: [{"id":605,"vote":1},{"id":606,"vote":-1},{"id":611,"vote":1},{"id":609,"vote":-1}] I attempt to iterate through the results and access the properties of each object: success: function (data) { $.each(da ...

How can I retrieve an attribute from another model in Ember using the current handlebar in the HTML file?

I'm attempting to achieve the following: {{#if model.user.isAdmin}} <div> My name is {{model.user.name}} </div> {{/if}} within a handlebar that is being used in a controller unrelated to users: <script type="text/x-handlebars" data- ...

Stripping CSS prefixes upon file initialization

When developing my application, I have a process in place where I load CSS files on the back-end using Express.JS and then transmit them to the front-end. However, before sending the CSS code to the front-end, I need to: Identify the user's browser; ...

Avoiding an event from spreading in Angular

I am working on a navigation setup that looks like this: <a (click)="onCustomParameters()"> <app-custom-start-card></app-custom-start-card> </a> When the user clicks on the app-custom-start-card, the onCustomParame ...

The publish-subscribe feature appears to be ineffective

Recently starting with meteor, I learned about the importance of removing autopublish. So, I decided to publish and subscribe to a collection in order to retrieve two different sets of values. Here is the code on my meteor side: Meteor.publish('chann ...

JavaScript array images are not showing when using the img tag

For this module, I am working on creating a flipbook (magazine) using images stored in a JavaScript array. However, I am facing an issue where the images are not loading up properly. Instead of displaying the image, it shows as [object" htmlimageelement]=" ...

Show only the image source (img src) and do not display the audio and video sources using jQuery

In my code, I need the following conditions to be met: when an image is posted from the backend, the video and audio sources should automatically hide; when a video is posted, the image and audio sources should hide; and when an audio file is posted, the v ...

Convert epoch time to HHMM format using JavaScript

I have a specific variable that stores epoch time data. My goal is to showcase the time information in HHMM format. Below you can find the code I am currently using; function convertEpochTimeToDateObj(epoch_time) { var utcSeconds = epoch_time; va ...

Exploring the power of Django: Leveraging AJAX requests and utilizing path

I am currently exploring ways to pass variables to a specific JavaScript file that initiates an AJAX request within Django. Assume we have a URL with a path parameter linking to a particular view: url(r'^post/(?P<post_id>\d+)/$', Tem ...

Unable to manipulate JQuery lightSlider slides using element index

I've been working on a new page design at this link: The code is still a work in progress, so bear with me as I test out some functions and scripts. At the end of the first section, there are 4 logos that, when clicked, will trigger a modal to pop u ...

Importing a file using its absolute path in JavaScript

Within the dependencies directory, there exists a module named foo: import foo from '../dependencies/foo'; // This import statement works as intended The challenge arises when attempting to import from a different path due to deployment in an AW ...