I'm trying to download a file on click of a button. My specific method is as follows:
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() }) },
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()