ajax 带token 的文件下载处理

实际上与带token 的图片处理类似

参考代码

<!DOCTYPE html>
<html lang="en">
 
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
 
<body>
 
    <input type="button" value="demoapp" onclick="demoapp()" />
    <script>
        function demoapp() {
            const url = "xxxxxxx";
            // 通过url 获取文件部分,可选,可以结合实际处理
            var re2 = /(https:\/\/)(.*)\/(.*)/;
            var fileNameRegx = url.match(re2);
            console.log(fileNameRegx[3])
            fetch(url, {
                method: 'GET', // or 'PUT'
                headers: {
                   // header 
                    "authorization": "deee"
                },
            })
                .then(res => res.blob())
                .then(data => {
                    var binaryData = [];
                    binaryData.push(data);
                    const url2 = window.URL.createObjectURL(new Blob(binaryData, {
                        type: "application/octet-stream"
                    }))
                    let a = document.createElement('a')
                    a.href = url2
                    a.download = decodeURIComponent(fileNameRegx[3])
                    document.body.appendChild(a)
                    a.click()
                    a.remove() // document.body.removeChild(a)
                    // 清理对象
                    URL.revokeObjectURL(url2)
                })
                .catch((error) => {
                    console.error('Error:', error);
                });
        }
    </script>
</body>
 
</html>

参考资料

https://www.cnblogs.com/rongfengliang/p/13751654.html

posted on   荣锋亮  阅读(166)  评论(0编辑  收藏  举报

相关博文:
阅读排行:
· 全程不用写代码,我用AI程序员写了一个飞机大战
· DeepSeek 开源周回顾「GitHub 热点速览」
· 记一次.NET内存居高不下排查解决与启示
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· .NET10 - 预览版1新功能体验(一)
历史上的今天:
2021-04-15 cube.js dremio driver 类型转换bug修改
2021-04-15 xfs 磁盘扩容
2021-04-15 cube.js 动态编译问题
2020-04-15 几个不错的开源formbuilder
2019-04-15 nginx ngx_http_image_filter_module 简单试用
2015-04-15 TaffyDB:开源JavaScript数据库
2014-04-15 html 滚动固定显示js脚本

导航

< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5
点击右上角即可分享
微信分享提示