美文网首页
前端下载文件操作

前端下载文件操作

作者: BuzzLightYearcc | 来源:发表于2020-08-07 15:20 被阅读0次

    ```javascript

    getExportList({ }) {

            this.exportFlag = true;

            this.exportTxt = '生成报表中···';

            this.exportPercent = 50;

            let xhr = new XMLHttpRequest();

            let that = this;

            const downloadUrl = '/deviceManager/device/report_export';

            xhr.onload = function (event) {

                if ((xhr.status >= 200 && xhr.status < 300) || xhr.status < 300) {

                    let type = xhr.getResponseHeader('Content-Type');

                    console.log(type);

                    //二进制文件流

                    if (type === 'application/octet-stream') {

                        let blob = new Blob([this.response])

                        var a = document.createElement('a');

                        a.style.display = 'none';

                        var url = window.URL.createObjectURL(blob);

                        var filename = decodeURIComponent(xhr.getResponseHeader('Content-Disposition')).split('=')[1];

                        a.href = url;

                        a.download = filename;

                        document.body.appendChild(a);

                        a.click();

                        window.URL.revokeObjectURL(url);

                        document.body.removeChild(a);

                        that.exportPercent = 100;

                        that.message.create('success', '报表已生成');

                        that.exportClass = true;

                        setTimeout(() => {

                            that.exportFlag = false;

                        }, 1000)

                    } else {

                        that.message.create('error', this.response.msg || '报表导出失败');

                        setTimeout(() => {

                            that.exportFlag = false;

                        }, 1000)

                    }

                } else {

                    that.message.create('error', this.response.msg || '报表导出失败');

                    setTimeout(() => {

                        that.exportFlag = false;

                    }, 1000)

                }

            };

            xhr.onprogress = (event) => {

                var divStatus = document.getElementById('status');

                console.log(event);

                if (event.lengthComputable) {

                    console.log(event);

                }

            };

            xhr.open('get', downloadUrl, true);

            xhr.responseType = 'blob';

            xhr.send(null);

        };

    ```

    重点是 xhr.responseType = 'blob';  要设置为blob  封装 保存的文件通过blob解析就会有问题

    相关文章

      网友评论

          本文标题:前端下载文件操作

          本文链接:https://www.haomeiwen.com/subject/btifdktx.html