純前端下載文件的方法

本文介紹純前端下載文件的方法。html

本文第一發布地址: http://www.cnblogs.com/ypinchina/p/8126102.html前端

本人不喜歡多廢話瀏覽器

需求,對於不少瀏覽器,若是隻知道下載對應url的狀況下,使用a標籤,點擊下載文件,會直接打開該文件,而不是下載文件。因而H5多了一個該死的屬性,'doload' 屬性。該屬性在 canIuse裏查兼容性,竟然連,IE11都不支持。所以,沒啥意思,因而發帖求了個能用的方法,兼容全部現代瀏覽器。以及IE11ide

如下是ES6的寫法:url

直接貼代碼。非ES6的狀況,本人概不負責,對於坐吃等死耗日子的開發,我沒啥好說的spa

export function downloadFile(fileName, url) {
if (isIE()) {
ieDown(url)
} else {
const aLink = document.createElement('a')
const evt = document.createEvent('MouseEvents')
evt.initMouseEvent('click', true, false, window, 0, 0, 0, 0, 0, false, false, false, false, 0, null)
aLink.download = fileName
aLink.href = url
aLink.dispatchEvent(evt)
}
}

const ieDown = url => {
window.open(url)
}

const isIE = () => {
const explorer = window.navigator.userAgent
return explorer.indexOf('MSIE') >= 0 || explorer.indexOf('Trident/7.0') >= 0 || explorer.indexOf('Edge') >= 0
}

 

 本文地址:http://www.cnblogs.com/ypinchina/p/8126102.htmlcode

完。htm

相關文章
相關標籤/搜索