ajax 请求pdf 下载文件流

今天需要把老系统的导出功能迁移到netcore3.1版本。

有vue版本和jquery版本的。导出方法不一样。

在使用ajax 异步请求导出PDF文件流,与vue还是有些差别。

废话不多说,直接上代码

 //数据导出
            $("#export").on("click", function () {
                var load = layer.msg('下载中...', {
                    icon: 16,
                    shade: [0.1, '#fff'],
                    time: false  //取消自动关闭
                });
                var shipid_ = (ship_==null ? ship_:$("#shiplist").val());
                console.log(shipid_);
                $.ajax({
                    url: getApiUrl() + "/api/Dc_Alarm/Export",
                    type: "get",
                    mimeType: 'text/plain; charset=x-user-defined',
                    headers: {
                        'Authorization': getJwtToken()
                    },
                    data: {
                        type: '1',
                        shipid: shipid_,
                        stime: $("#date1").val(),
                        etime: $("#date2").val(),
                        name: $("input[name='name']").val()
                    },
                    success: function (data) {
                        layer.close(load);
                        var rawLength = data.length;
                        var array = new Uint8Array(new ArrayBuffer(rawLength));
                        for (i = 0; i < rawLength; i++) {
                            array[i] = data.charCodeAt(i) & 0xff;
                        }
                        //上面是把后台请求到的文件流进行转化为符合的流
                        var blob = new Blob([array], { type: 'application/pdf;charset-UTF-8' });
                        var fileName = '安全帽告警.pdf';
                        if ('download' in document.createElement('a')) {
                            //非IE下载
                            const elink = document.createElement('a');
                            elink.download = fileName;
                            elink.style.display = 'none';
                            elink.href = URL.createObjectURL(blob);
                            document.body.appendChild(elink);
                            elink.click();
                            URL.revokeObjectURL(elink.href);
                            document.body.removeChild(elink);
                        } else {
                            navigator.msSaveBlob(blob, fileName);
                        }
                    }
                })

            })
            //

报layer错误的,引用layui.js就可以了。

转载自:https://www.51wzuan.cn

posted @ 2021-09-08 11:20  夜钓星云  阅读(136)  评论(0)    收藏  举报  来源