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 2022-04-15 21:37  荣锋亮  阅读(162)  评论(0编辑  收藏  举报

导航