Axios and CreateObjectURL: Correct way to download blob data? My attempt causes page reload

484 Views Asked by At

I have a button with a click event handler that, when clicked, will use axios to GET a file that resides on a remote server (passes a token and gets a blob responseType back). I don't understand how to use Url.createObjectURL with axios. What I am trying to do is have the browser download (or open?) a file when the user clicks the "download button" for that file. Unfortunately, my current attempt causes the browser to reload the page and append a # at the end of my Single page application with what I think is a hashed string?

How can I correctly download the file?

Here's my attempt:

async getDownloadAttachmentApiUrl(e) {
  const token = JSON.parse(localStorage.getItem('my-token'))
  const bearer = 'Bearer ' + token[0].access_token
  console.log(e.target.innerText) // example: attachments/5424/5424/24252345085_9cc011f4df_o.jpg
const instance = axios.create({
    baseURL: 'my-api-domain-here',
    responseType: 'blob',
    headers: {
      Authorization: bearer,
    }
  })
  try {
    const response = await instance.get('/Attachment?attachment=' + e.target.innerText)
    const objectURL = URL.createObjectURL(response.data)
    console.log(objectURL) // blob: https://lvh.me:8080/e6831f0d-b44f-4c50-b0c7-dc1389ee8cd7#/

The console log for objectURL is: https://lvh.me:8080/e6831f0d-b44f-4c50-b0c7-dc1389ee8cd7#/ which, when clicked, just causes the browser to reload the page and append the # at the end of the URL.

Here is the VueJS template code:

            <button v-for="(attachmentFileName, index) in attachmentsJsonObject.attachments" :key="index" @click.prevent="getDownloadAttachmentApiUrl">
              Download
            </button>

Thanks for any help/clarification on the proper way to set this up!

0

There are 0 best solutions below