我的url是一个.mp3格式的文件,我要触发这个方法时浏览器直接弹出下载 async function toDownLo

动态 未结 0 26
邮箱用户_b2v3t
邮箱用户_b2v3t LV1 2月18日 23:35 发表
摘要:
我的url是一个.mp3格式的文件,我要触发这个方法时浏览器直接弹出下载 async function toDownLoadAudio() { if (currentAudio.value === '') return try { const fileName = currentAudio.value.split('/').pop() // 获取最后一个斜杠后的部分作为文件名 // 通过代理服务器发起请求 const proxyUrl = `http://localhost:8080/proxy?url=${encodeURIComponent(currentAudio.value)}` const response = await fetch(proxyUrl) if (!response.ok) throw new Error('未能获取音频文件') const blob = await response.blob() const url = URL.createObjectURL(blob) const aLink = document.createElement('a') aLink.href = url aLink.download = fileName // 替换为实际文件名 aLink.style.display = 'none' document.body.appendChild(aLink) aLink.click() // 清理 URL.revokeObjectURL(url) document.body.removeChild(aLink) } catch (error) { console.error('下载音频时发生错误:', error) } }
为了实现点击链接直接弹出下载MP3文件的功能,我们需要对提供的JavaScript函数进行一些调整。我们需要确保函数在调用时能够通过创建一个隐藏的链接元素来触发浏览器的下载行为。以下是修改后的代码: ```javascript async function toDownLoadAudio() { if (currentAudio.value === '') return; try { const fileName = currentAudio.value.split('/').pop(); // 获取最后一个斜杠后的部分作为文件名 // 通过代理服务器发起请求 const proxyUrl = `http://localhost:8080/proxy?url=${encodeURIComponent(currentAudio.value)}`; const response = await fetch(proxyUrl); if (!response.ok) throw new Error('未能获取音频文件'); const blob = await response.blob(); const url = URL.createObjectURL(blob); const aLink = document.createElement('a'); aLink.href = url; aLink.download = fileName; // 设置下载的文件名 aLink.style.display = 'none'; // 隐藏该元素 document.body.appendChild(aLink); aLink.click(); // 模拟点击来下载文件 // 清理操作 URL.revokeObjectURL(url); document.body.removeChild(aLink); } catch (error) { console.error('下载音频时发生错误:', error); } } ``` 这段代码首先检查`currentAudio.value`是否为空,如果不为空,则从URL中提取文件名。然后通过代理服务器请求音频文件,如果请求成功,将响应转换为Blob对象,并创建一个不可见的链接元素。这个链接被设置为指向Blob对象的URL,并设置`download`属性为文件名,以指示浏览器下载文件而不是播放它。通过模拟点击这个链接,文件开始下载。最后,清理创建的URL和链接元素,避免内存泄漏。
收藏(0)  分享
相关标签: 智能问答
问题没解决?让AI助手帮你作答 AI助手
0个回复
  • 消灭零回复