Js点击按钮下载文件到本地(兼容多浏览器)
2018-03-21 14:38
766 查看
实现点击 用纯 js(非jquery) 下载文件到本地
自己尝试,加网上找了好久未果,如:
window.open(url) location.href=url form表单提交 iframe 体验和浏览器兼容都不完美
还是博客园一兄弟给了方法,非常感谢!
window.downloadFile = function (sUrl) { //iOS devices do not support downloading. We have to inform user about this. if (/(iP)/g.test(navigator.userAgent)) { alert('Your device does not support files downloading. Please try again in desktop browser.'); return false; } //If in Chrome or Safari - download via virtual link click if (window.downloadFile.isChrome || window.downloadFile.isSafari) { //Creating new link node. var link = document.createElement('a'); link.href = sUrl; if (link.download !== undefined) { //Set HTML5 download attribute. This will prevent file from opening if supported. var fileName = sUrl.substring(sUrl.lastIndexOf('/') + 1, sUrl.length); link.download = fileName; } //Dispatching click event. if (document.createEvent) { var e = document.createEvent('MouseEvents'); e.initEvent('click', true, true); link.dispatchEvent(e); return true; } } // Force file download (whether supported by server). if (sUrl.indexOf('?') === -1) { sUrl += '?download'; } window.open(sUrl, '_self'); return true; } window.downloadFile.isChrome = navigator.userAgent.toLowerCase().indexOf('chrome') > -1; window.downloadFile.isSafari = navigator.userAgent.toLowerCase().indexOf('safari') > -1;
相关文章推荐
- Js下载文件到本地(兼容多浏览器)
- 前台JS(type=‘file’)读取本地文件的内容,兼容各种浏览器
- JS实现点击按钮,下载文件
- 点击下载按钮下载文件到本地 download stream to local
- JS实现点击按钮,下载文件
- 前台JS(type=‘file’)读取本地文件的内容,兼容各种浏览器
- js读取本地xml文件 兼容IE Firfox Chrome 等浏览器
- 前台JS(type=‘file’)读取本地文件的内容,兼容各种浏览器 一
- JS实现点击按钮,下载文件
- js下载文件及命名(兼容多浏览器)
- 点击按钮下载本地文件
- js判断上传文件的大小,及确认文件是否在本地存在,兼容firefox、chrome、ie等浏览器
- clipboard.js 实现 点击按钮复制粘贴兼容ios 安卓 pc浏览器 zclip复制插件需要Flash支持
- php大力力 [029节] 做PHP项目如何下载js文件:使用腾讯浏览器把网上案例页面存储到本地
- JS实现点击按钮,下载文件
- 前台JS(type=‘file’)读取本地文件的内容,兼容各种浏览器 二
- JS下载文件的方法(浏览器兼容)
- 前台JS(type=‘file’)读取本地文件的内容,兼容各种浏览器 二
- 使用js实现点击按钮下载文件
- 使用JS代码实现点击按钮下载文件