前端解析二進制流實現文件下載和文件預覽(預覽只支持excel、圖片、pdf、txt文本)


很多時候需要純前端解析后台返回的二進制流進行文件的下載和預覽,此處主要是使用了xlsx.js文件和css文件,可自行在網上下載

實現下載:

 filedxz(path_, type_) {//附件下載
            let that = this;
            axios({
                method: 'get',
                url:url,
                headers: {
                    "auth": auth,
                },
                responseType: 'blob',//請求的關鍵,必須加上,負責無法成功(重中之重)
            }).then(response => {
                type_ = type_.toLowerCase();//轉小寫統一
                if (type_ == ".docx") {
                    that._type_ = "application/vnd.openxmlformats-officedocument.wordprocessingml.document"
                } else if (type_ == ".doc") {
                    that._type_ = "application/msword"
                } else if (type_ == ".gif") {
                    that._type_ = "image/gif"
                } else if (type_ == ".jpeg" || type_ == ".jpg") {
                    that._type_ = "image/jpeg"
                } else if (type_ == ".png") {
                    that._type_ = "image/png"
                } else if (type_ == ".pdf") {
                    that._type_ = "application/pdf"
                } else if (type_ == ".txt") {
                    that._type_ = "text/plain"
                } else if (type_ == ".xls") {
                    that._type_ = "application/vnd.ms-excel"
                } else if (type_ == ".xlsx") {
                    that._type_ = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
                } else if (type_ == ".xlsx") {
                    that._type_ = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
                } else if (type_ == ".zip") {
                    that._type_ = "application/zip"
                } else if (type_ == ".ppt") {
                    that._type_ = "application/vnd.ms-powerpoint"
                } else if (type_ == ".pptx") {
                    that._type_ = "application/vnd.openxmlformats-officedocument.presentationml.presentation"
                } else if (type_ == ".zip") {
                    that._type_ = "application/zip"
                }
                var blob = new Blob([response.data], { type: that._type_ })//第一個參數為數據
                var downloadElement = document.createElement('a');
                var href = window.URL.createObjectURL(blob); //創建下載的鏈接
                downloadElement.href = href;
                downloadElement.download = path_; //下載后文件名
                document.body.appendChild(downloadElement);
                downloadElement.click(); //點擊下載
                document.body.removeChild(downloadElement); //下載完成移除元素
                window.URL.revokeObjectURL(href); //釋放掉blob對象
            }).catch(function (err) {
                console.log(err);
            });
        },

文件預覽:

 filedyl(path, type_, name_) {
            debugger;
            let that = this;
            axios({
                method: 'get',
                url:url,
                headers: {
                    "auth": auth,
                },
                responseType: 'blob',//同樣是重點
            }).then(response => {
                type_ = type_.toLowerCase();
                if (type_ == ".docx") {
                    that._type_ = "application/vnd.openxmlformats-officedocument.wordprocessingml.document"
                } else if (type_ == ".doc") {
                    that._type_ = "application/msword"
                } else if (type_ == ".gif") {
                    that._type_ = "image/gif"
                } else if (type_ == ".jpeg" || type_ == ".jpg") {
                    that._type_ = "image/jpeg"
                } else if (type_ == ".png") {
                    that._type_ = "image/png"
                } else if (type_ == ".pdf") {
                    that._type_ = "application/pdf"
                } else if (type_ == ".txt") {
                    that._type_ = "text/plain;charset=utf-8'"
                } else if (type_ == ".xls") {
                    that._type_ = "application/vnd.ms-excel" 
                } else if (type_ == ".xlsx") {
                    that._type_ = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
                }else if (type_ == ".zip") {
                    that._type_ = "application/zip"
                } else if (type_ == ".ppt") {
                    that._type_ = "application/vnd.ms-powerpoint"
                } else if (type_ == ".pptx") {
                    that._type_ = "application/vnd.openxmlformats-officedocument.presentationml.presentation"
                }
                if (type_ == ".xlsx" || type_==".xls") {
                    $("#excelz").empty();//excel需要在預覽的地方自己加dom展示預覽
                    let  name =  name_.split(".")[0];//預覽文件的名字可以自行定義
                    var nContainer = document.getElementById('excelz');
                    var blob = new Blob([response.data], { type: that._type_ })
                    var href = window.URL.createObjectURL(blob); //創建下載的鏈接
                    var xlsx = new Plus.Xlsx(nContainer);
                    xlsx.readFile(href);
                    $("#excelz").prepend('<table id="table-preview" class="table table-striped table-hover"><thead style="width: 30%;"><tr><th>' + name + '</th></tr></thead></table>');
                    setTimeout(function () {
                        //去掉空行
                        // $("#excelz tr:gt(10)").each(function () {
                        //     var _hide = true;
                        //     $(this).find("td").each(function () {
                        //         if ($(this).text().trim() != '') {
                        //             _hide = false;
                        //         }
                        //     });
                        //     if (_hide) {
                        //         $(this).hide();
                        //     }
                        // });
                        //td為0時不顯示
                        $("#excelz tr td").each(function () {
                            if ($(this).text() == '0' || $(this).text() == '0.00' || $(this).text() == 0 || $(this).text() == 0.00) {
                                $(this).text("");
                            }
                        });
                        //去除表4最后一列空列
                        var _col_hide = true;
                        var len = $("table tr").length;
                        for (var i = 0; i < len; i++) {
                            if ($("#excelz tr").eq(i).find("td:last").text().trim() != '') {
                                _col_hide = false;
                            }
                        }
                        if (_col_hide) {
                            for (var i = 0; i < len; i++) {
                                $("#excelz tr").eq(i).find("td:last").remove();
                            }
                        }
                        $("#table-div, #close-table").show();
                    }, 500);
                } else {
                    var blob = new Blob([response.data], { type: that._type_ })
                    var href = window.URL.createObjectURL(blob); //創建下載的鏈接
                    window.open(href);
                }
            }).catch(function (err) {
                console.log(err);
            });
        },

從上面可以看出,實際上下載和預覽代碼基本一樣,所以可以通過一次請求來實現下載的同時並且提醒對方預覽,預覽文件要注意圖片、txt、pdf都是重新打開頁面實現預覽,excel是自己創建dom存放預覽信息,無法實現一個excel文件中有多個sheet文件的預覽,只能出現一個。

excel預覽效果:

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM