下载方法,移动端或者浏览器均可

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;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
移动打开默认浏览器下载文件的方法有多种,以下是一种常见的实现方式: 1. 首先,你需要在移动的网页中添加一个下载链接或按钮,用户点击该链接或按钮后会触发下载操作。 2. 在链接或按钮的点击事件中,可以使用 JavaScript 来处理下载操作。你可以使用以下代码示例来实现: ```javascript function downloadFile(url, filename) { // 创建一个隐藏的 <a> 元素 var link = document.createElement('a'); link.style.display = 'none'; link.href = url; link.download = filename; // 将 <a> 元素添加到 DOM 中 document.body.appendChild(link); // 触发点击事件进行下载 link.click(); // 移除 <a> 元素 document.body.removeChild(link); } // 在点击事件中调用 downloadFile() 函数来下载文件 var downloadButton = document.getElementById('download-button'); downloadButton.addEventListener('click', function() { var fileUrl = 'http://example.com/path/to/file'; // 文件的 URL var fileName = 'example-file.pdf'; // 文件名 downloadFile(fileUrl, fileName); }); ``` 在上述代码中,`downloadFile()` 函数接受两个参数:文件的 URL 和文件名。它创建一个隐藏的 `<a>` 元素,设置其 `href` 属性为文件的 URL,`download` 属性为文件名,然后将该元素添加到 DOM 中。接着,它通过模拟点击 `<a>` 元素来触发下载操作。最后,下载完成后,将 `<a>` 元素从 DOM 中移除。 请注意,上述代码中的 `fileUrl` 和 `fileName` 需要根据实际情况进行替换。 这样,当用户点击下载链接或按钮时,浏览器会自动下载文件,并保存到设备的默认下载目录中。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值