JS - 文件下载

文件下载 方法一

function downloadFile() {
    const link = document.createElement('a');
    link.style.display = 'none';
    link.setAttribute('href', file.sourceUrl); // 设置下载地址
    link.setAttribute('download', file.fileName); // 设置文件名
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);
}

文件下载 方法二

async function download(downloadUrl, downloadFileName) {
    const blob = await getBlob(downloadUrl);
    saveAs(blob, downloadFileName);
}



function getBlob(url) {
    return new Promise((resolve, reject) => {
        const xhr = new XMLHttpRequest();

        xhr.open('GET', url, true);
        xhr.responseType = 'blob';
        xhr.onload = () => {
            if (xhr.status === 200) {
                resolve(xhr.response);
            } else {
                reject(new Error(`Request failed with status ${xhr.status}`));
            }
        };
        xhr.onerror = () => {
            reject(new Error('Request failed'));
        };

        xhr.send();
    });
}



function saveAs(blob, filename) {
    if (window.navigator.msSaveOrOpenBlob) {
        navigator.msSaveBlob(blob, filename);
    } else {
        let link = document.createElement('a');
        const body = document.body;

        link.href = window.URL.createObjectURL(blob);
        link.download = filename;

        link.style.display = 'none'; // hide the link
        body.appendChild(link);

        link.click();
        body.removeChild(link);

        window.URL.revokeObjectURL(link.href);
    }
}

本文作者:ShenHaoCore

本文链接:https://www.cnblogs.com/ShenhaoCore/p/17965988

版权声明:本作品采用知识共享署名-非商业性使用-禁止演绎 2.5 中国大陆许可协议进行许可。

posted @   ShenHaoCore  阅读(47)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· DeepSeek 开源周回顾「GitHub 热点速览」
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· AI与.NET技术实操系列(二):开始使用ML.NET
· 单线程的Redis速度为什么快?
点击右上角即可分享
微信分享提示
评论
收藏
关注
推荐
深色
回顶
展开