Update href and download file on button click.
P粉170438285
P粉170438285 2023-07-20 15:17:03
0
1
544

I'm trying to download a file on click of a button. My specific method is as follows:

  1. On button click, I call an API that returns the buffered data of the file.
  2. Convert the buffered data to a base64 URL, and use this base64 URL to update the href attribute of the <a> element.
  3. Call the click event of the <a> element inside the function.

This method will download the file, but it will keep downloading the file indefinitely, I'm not sure why this is happening and don't know how to fix this.

This is how I call this function.

<button v-on:click="this.getImage([imageID, imageName], $event)"><a>View scoresheet</a></button>

This is the code of the function:

getImage: async function(info, event){
    fetch('endpoint' + String(info[0]) + "/" + String(info[1]) , {
        method: 'GET',
      
        })
        .then(response => response.json())
        .then(async result => {
             var image_data = await result.image_buffer.data
             var imgSrc = "data:image/jpg;base64," + btoa(
                 image_data.reduce((data, byte) => data + String.fromCharCode(byte), '')
             );

             event.target.href = imgSrc
             event.target.download = 'image.jpg'
             event.target.click()
        })
    },


P粉170438285
P粉170438285

reply all(1)
P粉807239416

The problem is that you reuse the same a element. So the click event fired at the end of getImage() triggers the click listener and getsImage() is called again, creating an infinite loop of getImage() calls.

To solve this problem, create a new a element in getImage() and use it as the "download" a of the script.

For example:


const el = document.createElement('a')

el.href = imgSrc
el.download = 'image.jpg'
el.click() 
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template