英文:
Update href and download file on button click
问题
我正在尝试在点击按钮时下载文件。我的确切方法如下:
- 在按钮点击时,我调用一个API,该API返回文件的缓冲数据。
- 将缓冲数据转换为base64 URL,并将
<a>
元素的href更新为这个base64 URL。 - 从函数内部调用
<a>
元素的点击事件。
这个方法会下载文件,但它会无限地重复下载文件,我不确定为什么会这样,并且不知道如何解决这个问题。
这是我调用函数的方式:
<button v-on:click="this.getImage([imageID, imageName], $event)"><a>查看成绩单</a></button>
这是函数的代码:
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()
})
},
英文:
I am trying to download a file on clicking a button. My exact approach is as follows:
- On the button click I call an API which returns the files Buffer Data
- Convert buffer data to a base64 url and update the href of the
<a>
element with this base64 url - invoke a click to the
<a>
element from inside the function
This approach will download the file, however, it keeps downloading the file infinitely and I'm not sure why its doing that and how to get around it.
Here is how I'm calling the function
<button v-on:click="this.getImage([imageID, imageName], $event)"><a>View scoresheet</a></button>
Here is 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()
})
},
答案1
得分: 2
问题在于你重复使用了相同的 a
元素。因此,在 getImage()
结束时触发的 click
事件会再次触发点击监听器,然后再次调用 getImage()
,导致了无限循环的 getImage()
调用。
要解决这个问题,在 getImage()
中创建一个新的 a
元素,并将其用作你脚本的 "download" a
。
例如:
const el = document.createElement('a')
el.href = imgSrc
el.download = 'image.jpg'
el.click()
英文:
The issue is that you are reusing the same a
element. Thus, the click
event triggered at the end of getImage()
triggers the click listener, and getImage()
is called again, creating an infinite loop of getImage()
calls.
To fix it, create a new a
element in getImage()
and use that as your script's "download" a
.
For example:
const el = document.createElement('a')
el.href = imgSrc
el.download = 'image.jpg'
el.click()
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论