proximacentauri
proximacentauri

Reputation: 1879

Vuejs with Axios how to open a file download dialog

I am trying work out how to open a file download dialog after an (Axios) Ajax request has been received from the (Flask) server.

Currently on the client I am using:

<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')
    })
  }
}

On the server I am using:

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

I get a response from the server OK, and the response contains valid header data, I just can't get a file download dialog to open.

Any clues?

Upvotes: 2

Views: 5631

Answers (1)

zshanabek
zshanabek

Reputation: 4770

You have to add responseType

axios(url: 'http://localhost:5000/exportdata',
     method: 'GET',
     responseType: 'blob', // important
      }
    )
    .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) // for firefox
    })

Upvotes: 1

Related Questions