zoukankan      html  css  js  c++  java
  • pdf.js-----后端返回utf-8数据流,前端处理数据展示pdf

    需求:做项目联调接口时,发现知识库展示pdf未果,经与后端人员沟通,发现以下问题:

               1.接口返回的是utf-8数据流,但是前端调用的是base64解析方法;

                  导致功能有误;

    方案一:将后端返回的utf-8数据流改为经base64解析的数据流。    ========新思路:尝试缓加载,但是未能实现。

                测试结果:安卓系统可以正常使用,但是ios当时存在闪退的问题,且base64若处理一个2M的文件,解析后体积将近为4M,对小文件还是用,大文件很容易造成系统运行内存不够,跳出App。

    方案二:用iframe静态展示base64文件流。

                测试结果:ios可正常使用,但是安卓系统对iframe存在兼容性问题。

    <iframe  ng-src="{{pdfPath}}"  style="100%;height:800px;"> </iframe>

    方案三:将后端数据流退回到utf-8,修改解析后端返回数据流的方法。------解决问题。

    1     <div style=" 100%;"  ng-style="{height: screenHeight-160 + 'px'}">
    2           <div id="pdf-containerTF"  style=" 100%; height: 100%;border-radius: 10px; box-shadow: 0 0 10px #3268d2; background: #ffffff;padding: 0 5px;margin-top:5px;">
    3                   <ion-scroll delegate-handle="pdfScroll" zooming="true" direction="xy" style=" 100%; height: 100%;" scrollbar-y="false" scrollbar-x="false" min-zoom="1">
    4                         <div id="pdf-popTF"  style=" 100%; height: 100%;border-radius: 10px; background: #ffffff;position: absolute;padding: 0px;">
    5                         </div>
    6                     </ion-scroll>
    7               </div>
    8      </div>            
     $scope.getFileData=function () {
               var params={
                    fileId:$scope.fileId
                    }
             $ionicLoading.show({});
              yxxPdfHttp.post(QUERY_SERVICE_FILE_DATA,params, function (data) {
                        if(data){
                            $ionicLoading.hide({});
                            $scope.fileDataObj.fileTitle=$scope.fileTitle;
                            showPdfFileM(data);
                            $rootScope.isRefresh = true;
                        }else{
                            $ionicLoading.hide({});
                            alert({type: '', title: '温馨提示', msg: "请求发生异常"});
                        }
                    }, function (data) {
                        $ionicLoading.hide({});
                        alert({type:'',title: '错误',msg:'服务器繁忙,请稍后重试!'});
                    });
        }
    

      

    封装专用于请求数据流的ajax请求
    //封装接收pdf的ajax
        .factory('yxxPdfHttp', ["$http", "$rootScope", "$timeout", function ($http, $rootScope, $timeout) {
            var url = "";
            return {
                post: function (method, params, success, error, config) {
                    // console.log(params)
                    var head = {
                        accepts: '*/*',
                        Authorization: 'Bearer ' + $rootScope.Authorization
                    };
                    if (method == QUERY_LOGIN_TOKEN) {
                        head = {
                            accepts: '*/*'
                        };
                    }
                    var asflag = true;
                    if (config) {
                        if ('async' in config) {
                            asflag = config.async;
                        }
                    }
                    $.ajax({
                        type: "post",
                        url: serverPath + method,
                        contentType: 'application/json',
                        // responseType:'multipart/form-data',
                        mimeType: 'text/plain; charset=x-user-defined',  
                        dataType: 'text',
                        headers: head,
                        timeout: 180000,
                        async: asflag,
                        data: JSON.stringify(params),
                        success: function (data, status, xhr) {
                            // success(JSON.parse(data));
                            success(data);
                            //    console.log(data);
                        },
                        complete: function (request, textStatus) {
                            if (textStatus == 'timeout') {
                                alert({ type: 'error', title: '温馨提示', msg: "请求超时" });
                                $timeout(function () { $rootScope.$apply() })
                            }
                        },
                        error: function (request, data, exception) {
                            error(request.responseJSON);
                            console.log(request);
                            console.log(data);
                            if (request.readyState == 0 && request.status == 0) {
                                console.log(request.readyState);
                                console.log(request.status);
                            } else if (request && request.status != 200) {
                                //在非登录页token 失效调原生方法回到登录页
                                if (request.status == 401) {
                                    if (window.webkit) {
                                        window.webkit.messageHandlers.authfailed.postMessage({
                                            params: {
                                                code: false
                                            }
                                        })
                                    } else {
                                        nativeObj.backLogin("88");
                                    }
                                } else {
                                    var message = '';
                                    if (request.responseJSON) {
                                        message = request.responseJSON.message;
                                    } else if (request.responseText) {
                                        message = JSON.parse(request.responseText).message;
                                    } else {
                                        message = '请求异常';
                                    }
                                    alert({ type: '', title: request.status + ':' + method + ':' + request.getResponseHeader('request_id'), msg: message });
                                }
                            } else {
                                alert({ type: 'error', title: '错误', msg: "系统异常请联系管理员。" });
                            }
                            $timeout(function () { $rootScope.$apply() })
                        }
    
                    });
                }
            };
        }])
    

      

    修改封装解析utf-8的方法
    var showPdfFileM = function (pdf) {
        // var DEFAULT_URL = "";//注意,删除的变量在这里重新定义  
        // var PDFData = "";
        var rawLength = pdf.length;
        //转换成pdf.js能直接解析的Uint8Array类型,见pdf.js-4068  
        var array = new Uint8Array(new ArrayBuffer(rawLength));
        for (i = 0; i < rawLength; i++) {
            array[i] =pdf.charCodeAt(i) & 0xff;
        }
        // DEFAULT_URL = array;
    
        // var data = char2buf(window.atob(pdf));
        var data = array;
        pdfjsLib.getDocument({
            data: data,
            cMapUrl: 'lib/pdf.js/web/cmaps/',
            cMapPacked: true
        }).then(function (pdfDoc_) {
            pdfDoc = pdfDoc_;
            count = pdfDoc.numPages;
            //绘制所有的页面
            renderAllTF();
        });
  • 相关阅读:
    LeetCode 189. Rotate Array
    LeetCode 965. Univalued Binary Tree
    LeetCode 111. Minimum Depth of Binary Tree
    LeetCode 104. Maximum Depth of Binary Tree
    Windows下MySQL的安装与配置
    LeetCode 58. Length of Last Word
    LeetCode 41. First Missing Positive
    LeetCode 283. Move Zeroes
    《蚂蚁金服11.11:支付宝和蚂蚁花呗的技术架构及实践》读后感
    删除docker下的镜像
  • 原文地址:https://www.cnblogs.com/linm/p/12320689.html
Copyright © 2011-2022 走看看