js如何实现文件下载呢?(ppt,img,text等都是下载),弹出保存选项框那种的?

如题,网上百度了很多,基本上实现不了 ,还有很多错误,有没有大神做过的,提示个思路或者需要用到什么插件吗?

阅读 10k
4 个回答

用H5的新属性

<a href="js/contact.js" download="newName.js">下载JS</a>
var  e = document.createEvent('MouseEvents');
var  a = document.createElement('a');

a.download = '404.svg';
a.href = 'https://sf-static.b0.upaiyun.com/v-58bd1fcb/global/img/404.svg';
if(confirm('您确定要下载吗?')){
    e.initMouseEvent('click', true, false, window, 0, 0, 0, 0, 0, false, false, false, false, 0, null);
    a.dispatchEvent(e);
}

后台给一个下载接口就好,这样可以兼容所有浏览器,还可以附加下载统计功能呢!

<!DOCTYPE html>
<html>
<head>
    <title></title>
</head>
<body>
    <script type="text/javascript">
        function downFile(blob, fileName) {
            if (window.navigator.msSaveOrOpenBlob) {
                navigator.msSaveBlob(blob, fileName);
            } else {
                var link = document.createElement('a');
                link.href = window.URL.createObjectURL(blob);
                link.download = fileName;
                link.click();
                window.URL.revokeObjectURL(link.href);
            }
        }
        blob = new Blob(['文件内容:hello world !'], {type: "application/octet-binary"});
        fileName = '文件名称.txt';
    </script>
    <button onclick="downFile(blob, fileName);">点我生成txt文件</button>
</body>
</html>
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题