前端_二进制流文件下载和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 @ 2022-03-10 14:40  城南以南123  阅读(376)  评论(0编辑  收藏  举报