js 瀏覽器直接下載文件(不借助服務(wù)器)

需求:前端通過瀏覽器直接下載public下的文件。

思路:靜態(tài)資源可以利用a標(biāo)簽或者借助函數(shù)方法下載。

將靜態(tài)資源文件直接放于public目錄下,打包時(shí)public文件不會(huì)被編譯。

1.利用a標(biāo)簽下載

<a href="/HCWebSDKPlugin.exe" download="HCWebSDKPlugin.exe">插件下載</a>

靜態(tài)資源的路徑,在public文件夾下路徑是/文件名

2.借助函數(shù)方法下載

/* 
@param {string} url  靜態(tài)資源url
@param {string} filename  靜態(tài)資源文件名
@param {string} target  
*/
const fileUrlHandled = ({ url, filename, target }) => {
    const downloadElement = document.createElement('a')
    downloadElement.style.display = 'none'
    downloadElement.href = url
    if (target) {
        downloadElement.target = '_blank'
    }
    downloadElement.rel = 'noopener noreferrer'
    if (filename) {
        downloadElement.download = filename
    }
    document.body.appendChild(downloadElement)
    downloadElement.click()
    document.body.removeChild(downloadElement)
}
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容