前端_二进制流文件下载和URL文件下载

二进制流文件下载

复制代码
        function downloadFileByBinary(fileKey: string, fileName: string) {
            axios({
                method: 'get',
                url: 'xxxx',
                params: {
                    fileKey: fileKey
                },
                headers: {
                    'Content-type': 'text/json'
                },
                responseType: 'blob'
            }).then((response: any) => {
                const data = response.data;
                const reader = new FileReader();
                reader.onload = function() {
                    const url = window.URL.createObjectURL(new Blob([data]));
                    const link = document.createElement('a');
                    link.style.display = 'none';
                    link.href = url;
                    link.download = fileName;
                    document.body.appendChild(link);
                    link.click();
                    document.body.removeChild(link);
                    window.URL.revokeObjectURL(url);
                };
                reader.readAsArrayBuffer(data);
            });
        }
复制代码

URL文件下载

复制代码
        function downloadFileByUrl(url: string, fileName: string) {
            getBlob(url, (blob) => {
                saveAs(blob, fileName);
            })
        }
        function getBlob(url, cb) {
            const xhr = new XMLHttpRequest();
            xhr.open('GET', url, true);
            xhr.responseType = 'blob';
            xhr.onload = () => {
                if (xhr.status === 200) {
                    cb(xhr.response);
                }
            };
            xhr.send();
        }
        function saveAs(blob, fileName) {
            if (window, navigator.msSaveOrOpenBlob) {
                navigator.msSaveBlob(blob, fileName);
            } else {
                const link = document.createElement('a');
                link.style.display = 'none';
                link.href = url;
                link.download = fileName;
                document.body.appendChild(link);
                link.click();
                document.body.removeChild(link);
                window.URL.revokeObjectURL(url);
            }
        }
复制代码

 

posted @   城南以南123  阅读(389)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· 单线程的Redis速度为什么快?
· SQL Server 2025 AI相关能力初探
· AI编程工具终极对决:字节Trae VS Cursor,谁才是开发者新宠?
· 展开说说关于C#中ORM框架的用法!
点击右上角即可分享
微信分享提示