Просмотр исходного кода

1、修复PDF单点下载失败问题

huangmp 2 лет назад
Родитель
Сommit
dc97eb5935
1 измененных файлов с 73 добавлено и 53 удалено
  1. 73 53
      src/views/modules/print/printList.vue

+ 73 - 53
src/views/modules/print/printList.vue

@@ -25,8 +25,9 @@
     </div>
     <div class="main-container">
       <div class="operation-bar">
-        <div class=" default-btn" @click="downLoadZIP()"
-             :disabled="importDisabled">批量下载ZIP</div>
+        <el-button size="small" @click="downLoadZIP()" :loading="downloadLoading">批量下载</el-button>
+        <!--<div class=" default-btn" @click="downLoadZIP()"
+             :disabled="importDisabled">批量下载ZIP</div>-->
       </div>
       <div class="table-con">
         <el-table :data="dataList" header-cell-class-name="table-header" row-class-name="table-row-low"
@@ -61,14 +62,15 @@
 </template>
 
 <script>
-  import JSzip from 'jszip';
-  import { saveAs } from 'file-saver';
+  import JSzip from 'jszip'
+import { saveAs } from 'file-saver'
+import axios from 'axios'
 
-  export default {
-    data() {
+export default {
+    data () {
       return {
         theData: null, // 保存上次点击查询的请求条件
-
+        downloadLoading: false,
         dataList: [],
         dataListLoading: false,
         exportDisabled: false,
@@ -94,7 +96,7 @@
           orderNumber: undefined,
           startTime: undefined, // 起始时间
           endTime: undefined, // 结束时间,
-          pdfName: null,
+          pdfName: null
         },
         levelTypes: [
           {
@@ -118,12 +120,12 @@
     },
     components: {
     },
-    mounted() {
+    mounted () {
       this.getDataList(this.page)
     },
     methods: {
-      deletePdf(pdf){
-        this.$confirm("确定要删除PDF文件吗"+ '?', "提示", {
+      deletePdf (pdf) {
+        this.$confirm('确定要删除PDF文件吗' + '?', '提示', {
           confirmButtonText: this.$i18n.t('crud.filter.submitBtn'),
           cancelButtonText: this.$i18n.t('crud.filter.cancelBtn'),
           type: 'warning'
@@ -136,34 +138,47 @@
             this.$message({
               message: this.$i18n.t('publics.operation'),
               type: 'success',
-              duration: 200,
-            });
+              duration: 200
+            })
             this.getDataList(this.page)
           })
         }).catch(() => { })
       },
-      downLoadPDF(pdf) {
-        let randomStr = Math.floor(Math.random() * 100000).toString();
-        this.getPdfFile(this.resourcesUrl + pdf.pdfUrl + "?a=" + randomStr).then(data => {
+      downLoadPDF (pdf) {
+        let randomStr = Math.floor(Math.random() * 100000).toString()
+        this.getPdfFile(this.resourcesUrl + pdf.pdfUrl + '?a=' + randomStr).then(data => {
           saveAs(data, pdf.pdfName)
         })
       },
-      getPdfFile(url) {
+      getPdfFile (url) {
         return new Promise((resolve, reject) => {
-          let xmlhttp = new XMLHttpRequest();
-          xmlhttp.open("GET", url, true);
-          xmlhttp.responseType = "blob";
-          xmlhttp.onload = function () {
-            if (this.status == 200) {
-              resolve(this.response);
-            } else {
-              reject(this.status);
-            }
-          }
-          xmlhttp.send();
-        });
+          axios({
+            method: 'get', // 使用get请求
+            url, // 放入的文件地址
+            responseType: 'blob' // 请求的数据buffer对象
+          })
+            .then((data) => {
+              resolve(data.data)
+            })
+            .catch((error) => {
+              reject(error.toString())
+            })
+        })
+        // return new Promise((resolve, reject) => {
+        //   let xmlhttp = new XMLHttpRequest();
+        //   xmlhttp.open("GET", url, true);
+        //   xmlhttp.responseType = "arraybuffer";
+        //   xmlhttp.onload = function () {
+        //     if (this.status == 200) {
+        //       resolve(this.response);
+        //     } else {
+        //       reject(this.status);
+        //     }
+        //   }
+        //   xmlhttp.send();
+        // });
       },
-      getAllNeed() {
+      getAllNeed () {
         if (!this.theData) {
           this.theData = JSON.parse(JSON.stringify(this.searchForm))
         }
@@ -181,51 +196,56 @@
           )
         }).then(({ data }) => {
           console.log(data.records)
-          let pdfList = data.records;
+          let pdfList = data.records
           // const arr = [{fileDownUrl:'地址', fileDownName:'文件名'}] // 需要下载打包的路径, 可以是本地相对路径, 也可以是跨域的全路径
           const zip = new JSzip()
           const cache = {}
           const promises = []
           pdfList.forEach((pdf, j) => {
-            let randomStr = Math.floor(Math.random() * 100000).toString();
-            const promise = this.getPdfFile(this.resourcesUrl + pdf.pdfUrl + "?a=" + randomStr).then(data => {
+            let randomStr = Math.floor(Math.random() * 100000).toString()
+            const promise = this.getPdfFile(this.resourcesUrl + pdf.pdfUrl + '?a=' + randomStr).then(data => {
               // 下载文件, 并存成blob对象
-              const fileName = pdf.pdfFolderName + "/" + pdf.pdfName; // 获取文件名,一定要包含文件的后缀名(因为重复的文件名只会下载一个,故需要加入下标 不同名)
-              // zip.folder(pdf.pdfFolderName).file(pdf.pdfName, data);
-              zip.file(pdf.pdfName, data);
-              cache[fileName] = data
+              // const fileName = pdf.pdfFolderName + "/" + pdf.pdfName; // 获取文件名,一定要包含文件的后缀名(因为重复的文件名只会下载一个,故需要加入下标 不同名)
+              zip.file(pdf.pdfName, data, {
+                binary: true
+              })
+              cache[pdf.pdfName] = data
             })
             promises.push(promise)
-          });
+          })
           Promise.all(promises).then(() => {
-            zip.generateAsync({ type: "blob" }).then(content => {
+            zip.generateAsync({ type: 'blob' }).then(content => {
               // 生成二进制流   然后保存文件(如果这个下载不了 也可以将下方这一行换成a标签下载逻辑)
-              saveAs(content, "批量下载PDF压缩包.zip") // 利用file-saver保存文件  自定义文件名
-              // this.wavePrintOrderPdfDownloadLoading = false;
+              saveAs(content, '批量下载PDF压缩包.zip') // 利用file-saver保存文件  自定义文件名
+              this.downloadLoading = false
             })
+            // eslint-disable-next-line handle-callback-err
+          }).catch((error) => {
+            this.downloadLoading = false
           })
-        });
+        })
       },
-      downLoadZIP() {
+      downLoadZIP () {
         if (!!this.searchForm.startTime && !!this.searchForm.endTime) {
+          this.downloadLoading = true
           if ((Date.parse(new Date(this.searchForm.endTime).toString()) - Date.parse(new Date(this.searchForm.startTime).toString())) / 1000 / 60 / 60 <= 24) {
             this.getAllNeed()
           } else {
             this.$message({
               message: '批量下载ZIP范围最大为24小时',
               type: 'warning'
-            });
+            })
           }
         } else {
           this.$message({
             message: '请先选择创建时间,范围最大为24小时',
             type: 'warning'
-          });
+          })
         }
       },
 
       // 获取数据列表  /admin/user/page
-      getDataList(page, newData = false) {
+      getDataList (page, newData = false) {
         if (newData || !this.theData) {
           this.theData = JSON.parse(JSON.stringify(this.searchForm))
         }
@@ -250,19 +270,19 @@
         })
       },
       // 条件查询 JSON.stringify(arr)
-      searchChange(newData = false) {
+      searchChange (newData = false) {
         this.page.currentPage = 1
         this.getDataList(this.page, newData)
       },
-      handleSizeChange(val) {
+      handleSizeChange (val) {
         this.page.pageSize = val
         this.getDataList(this.page)
       },
-      handleCurrentChange(val) {
+      handleCurrentChange (val) {
         this.page.currentPage = val
         this.getDataList(this.page)
       },
-      resetForm(formName) {
+      resetForm (formName) {
         this.$refs[formName].resetFields()
         this.searchForm.startTime = undefined
         this.searchForm.endTime = undefined
@@ -271,7 +291,7 @@
         this.theData = null
         this.getDataList(this.page)
       },
-      createTimeChange() {
+      createTimeChange () {
         if (!this.createDateRange || this.createDateRange.length === 0) {
           this.searchForm.startTime = undefined
           this.searchForm.endTime = undefined
@@ -282,9 +302,9 @@
         this.searchChange(true)
       },
       // 多选变化
-      selectionChange(val) {
+      selectionChange (val) {
         this.dataListSelections = val
-      },
+      }
     }
   }
 </script>