IE浏览器下载文件会自动打开,无弹框保存

JS弹框下载文件方法

function DownloadFile(sUrl, reName) {
    if (window.downloadFile.isChrome || window.downloadFile.isSafari) {
        //Creating new link node.
        var link = document.createElement('a');
        link.href = sUrl;

        if (link.download !== undefined) {
            var fileName = reName;
            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;

DownloadFile('http://xxx/Log/default.cfg', 'data.cfg')

但是此方法不支持IE浏览器,可需求要支持IE下载。

现象

IE浏览器请求服务器上文本文件(.txt,json,.cgf等等)时, 浏览器会自动打开

解决方法

后台:将请求响应头(Request Headers)的Content-Disposition(内容部署)设置为attachment。

在这里插入图片描述
有两种部署类型:inline和attachment
inline :将文件内容直接显示在页面
attachment:弹出对话框让用户下载

前端:修改DownloadFile()方法
function DownloadFile(sUrl, reName)
{ 
    var Link = document.createElement('a');
    Link.href = sUrl;
    if (Link.download !== undefined) 
    {
        //var CurrentTime = new Date().toLocaleString();
        var FileName = reName;    
        Link.download = FileName;
    }

    if (document.createEvent) 
    {
        var E = document.createEvent('MouseEvents');
        E.initEvent('click', true, true);
        Link.dispatchEvent(E);
        return true;
    }
}
完美解决:

在这里插入图片描述

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值