From 7fcb1b2e0af2d50617ef2e7c04bd639de75c99a9 Mon Sep 17 00:00:00 2001
From: RuoYi <yzz_ivy@163.com>
Date: Mon, 27 Sep 2021 12:10:39 +0800
Subject: [PATCH] 新增通用方法简化下载使用

---
 ruoyi-ui/src/utils/request.js                                                                |   32 ++++------
 /dev/null                                                                                    |   42 --------------
 ruoyi-ui/src/views/tool/gen/index.vue                                                        |    3 
 ruoyi-ui/src/plugins/index.js                                                                |    3 +
 ruoyi-ui/src/views/tool/build/index.vue                                                      |   19 +-----
 ruoyi-common/ruoyi-common-core/src/main/java/com/ruoyi/common/core/utils/file/FileUtils.java |    1 
 ruoyi-ui/src/plugins/download.js                                                             |   24 ++++++++
 7 files changed, 45 insertions(+), 79 deletions(-)

diff --git a/ruoyi-common/ruoyi-common-core/src/main/java/com/ruoyi/common/core/utils/file/FileUtils.java b/ruoyi-common/ruoyi-common-core/src/main/java/com/ruoyi/common/core/utils/file/FileUtils.java
index 6938a2b..f76bb34 100644
--- a/ruoyi-common/ruoyi-common-core/src/main/java/com/ruoyi/common/core/utils/file/FileUtils.java
+++ b/ruoyi-common/ruoyi-common-core/src/main/java/com/ruoyi/common/core/utils/file/FileUtils.java
@@ -244,6 +244,7 @@
                 .append(percentEncodedFileName);
 
         response.setHeader("Content-disposition", contentDispositionValue.toString());
+        response.setHeader("download-filename", percentEncodedFileName);
     }
 
     /**
diff --git a/ruoyi-ui/src/plugins/download.js b/ruoyi-ui/src/plugins/download.js
new file mode 100644
index 0000000..bc838fd
--- /dev/null
+++ b/ruoyi-ui/src/plugins/download.js
@@ -0,0 +1,24 @@
+import { saveAs } from 'file-saver'
+import axios from 'axios'
+import { getToken } from '@/utils/auth'
+
+const baseURL = process.env.VUE_APP_BASE_API
+
+export default {
+  zip(url, name) {
+    var url = baseURL + url
+    axios({
+      method: 'get',
+      url: url,
+      responseType: 'blob',
+      headers: { 'Authorization': 'Bearer ' + getToken() }
+    }).then(res => {
+      const blob = new Blob([res.data], { type: 'application/zip' })
+      this.saveAs(blob, name)
+    })
+  },
+  saveAs(text, name, opts) {
+    saveAs(text, name, opts);
+  }
+}
+
diff --git a/ruoyi-ui/src/plugins/index.js b/ruoyi-ui/src/plugins/index.js
index 15d829b..a138e6d 100644
--- a/ruoyi-ui/src/plugins/index.js
+++ b/ruoyi-ui/src/plugins/index.js
@@ -1,5 +1,6 @@
 import cache from './cache'
 import modal from './modal'
+import download from './download'
 
 export default {
   install(Vue) {
@@ -7,5 +8,7 @@
     Vue.prototype.$cache = cache
     // 模态框对象
     Vue.prototype.$modal = modal
+    // 下载文件
+    Vue.prototype.$download = download
   }
 }
diff --git a/ruoyi-ui/src/utils/request.js b/ruoyi-ui/src/utils/request.js
index 48b36e8..6db38ba 100644
--- a/ruoyi-ui/src/utils/request.js
+++ b/ruoyi-ui/src/utils/request.js
@@ -1,11 +1,14 @@
 import axios from 'axios'
-import { Notification, MessageBox, Message } from 'element-ui'
+import { Notification, MessageBox, Message, Loading } from 'element-ui'
 import store from '@/store'
 import { getToken } from '@/utils/auth'
 import errorCode from '@/utils/errorCode'
 import { tansParams } from "@/utils/ruoyi";
+import { saveAs } from 'file-saver'
 
-axios.defaults.headers['Content-Type'] = 'application/json;charset=utf-8'
+let downloadLoadingInstance;
+
+axios.defaults.headers['Conntent-Type'] = 'application/json;charset=utf-8'
 // 创建axios实例
 const service = axios.create({
   // axios中请求配置有baseURL选项,表示请求URL公共部分
@@ -90,31 +93,20 @@
 
 // 通用下载方法
 export function download(url, params, filename) {
+  downloadLoadingInstance = Loading.service({ text: "正在下载数据,请稍后", spinner: "el-icon-loading", background: "rgba(0, 0, 0, 0.7)", })
   return service.post(url, params, {
-    transformRequest: [(params) => {
-      return tansParams(params)
-    }],
-    headers: {
-        'Content-Type': 'application/x-www-form-urlencoded'
-    },
+    transformRequest: [(params) => { return tansParams(params) }],
+    headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
     responseType: 'blob'
   }).then((data) => {
     const content = data
     const blob = new Blob([content])
-    if ('download' in document.createElement('a')) {
-      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)
-    }
+    saveAs(blob, filename)
+    downloadLoadingInstance.close();
   }).catch((r) => {
     console.error(r)
+    Message.error('下载文件出现错误,请联系管理员!')
+    downloadLoadingInstance.close();
   })
 }
 
diff --git a/ruoyi-ui/src/utils/zipdownload.js b/ruoyi-ui/src/utils/zipdownload.js
deleted file mode 100644
index 8a1b819..0000000
--- a/ruoyi-ui/src/utils/zipdownload.js
+++ /dev/null
@@ -1,42 +0,0 @@
-import axios from 'axios'
-import { getToken } from '@/utils/auth'
-
-const mimeMap = {
-  xlsx: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
-  zip: 'application/zip'
-}
-
-const baseUrl = process.env.VUE_APP_BASE_API
-export function downLoadZip(str, filename) {
-  var url = baseUrl + str
-  axios({
-    method: 'get',
-    url: url,
-    responseType: 'blob',
-    headers: { 'Authorization': 'Bearer ' + getToken() }
-  }).then(res => {
-    resolveBlob(res, mimeMap.zip)
-  })
-}
-/**
- * 解析blob响应内容并下载
- * @param {*} res blob响应内容
- * @param {String} mimeType MIME类型
- */
-export function resolveBlob(res, mimeType) {
-  const aLink = document.createElement('a')
-  var blob = new Blob([res.data], { type: mimeType })
-  // //从response的headers中获取filename, 后端response.setHeader("Content-disposition", "attachment; filename=xxxx.docx") 设置的文件名;
-  var patt = new RegExp('filename=([^;]+\\.[^\\.;]+);*')
-  var contentDisposition = decodeURI(res.headers['content-disposition'])
-  var result = patt.exec(contentDisposition)
-  var fileName = result[1]
-  fileName = fileName.replace(/\"/g, '')
-  aLink.style.display = 'none'
-  aLink.href = URL.createObjectURL(blob)
-  aLink.setAttribute('download', fileName) // 设置下载文件名称
-  document.body.appendChild(aLink)
-  aLink.click()
-  URL.revokeObjectURL(aLink.href);//清除引用
-  document.body.removeChild(aLink);
-}
diff --git a/ruoyi-ui/src/views/tool/build/index.vue b/ruoyi-ui/src/views/tool/build/index.vue
index 0281d18..e511408 100644
--- a/ruoyi-ui/src/views/tool/build/index.vue
+++ b/ruoyi-ui/src/views/tool/build/index.vue
@@ -137,23 +137,13 @@
 
 <script>
 import draggable from 'vuedraggable'
-import { saveAs } from 'file-saver'
 import beautifier from 'js-beautify'
 import ClipboardJS from 'clipboard'
 import render from '@/utils/generator/render'
 import RightPanel from './RightPanel'
-import {
-  inputComponents,
-  selectComponents,
-  layoutComponents,
-  formConf
-} from '@/utils/generator/config'
-import {
-  exportDefault, beautifierConf, isNumberStr, titleCase
-} from '@/utils/index'
-import {
-  makeUpHtml, vueTemplate, vueScript, cssStyle
-} from '@/utils/generator/html'
+import { inputComponents, selectComponents, layoutComponents, formConf } from '@/utils/generator/config'
+import { beautifierConf, titleCase } from '@/utils/index'
+import { makeUpHtml, vueTemplate, vueScript, cssStyle } from '@/utils/generator/html'
 import { makeUpJs } from '@/utils/generator/js'
 import { makeUpCss } from '@/utils/generator/css'
 import drawingDefalut from '@/utils/generator/drawingDefalut'
@@ -161,7 +151,6 @@
 import CodeTypeDialog from './CodeTypeDialog'
 import DraggableItem from './DraggableItem'
 
-const emptyActiveData = { style: {}, autosize: {} }
 let oldActiveId
 let tempActiveData
 
@@ -287,7 +276,7 @@
     execDownload(data) {
       const codeStr = this.generateCode()
       const blob = new Blob([codeStr], { type: 'text/plain;charset=utf-8' })
-      saveAs(blob, data.fileName)
+      this.$download.saveAs(blob, data.fileName)
     },
     execCopy(data) {
       document.getElementById('copyNode').click()
diff --git a/ruoyi-ui/src/views/tool/gen/index.vue b/ruoyi-ui/src/views/tool/gen/index.vue
index fcc9f62..1f24fa9 100644
--- a/ruoyi-ui/src/views/tool/gen/index.vue
+++ b/ruoyi-ui/src/views/tool/gen/index.vue
@@ -180,7 +180,6 @@
 <script>
 import { listTable, previewTable, delTable, genCode, synchDb } from "@/api/tool/gen";
 import importTable from "./importTable";
-import { downLoadZip } from "@/utils/zipdownload";
 import hljs from "highlight.js/lib/highlight";
 import "highlight.js/styles/github-gist.css";
 hljs.registerLanguage("java", require("highlight.js/lib/languages/java"));
@@ -270,7 +269,7 @@
           this.$modal.msgSuccess("成功生成到自定义路径:" + row.genPath);
         });
       } else {
-        downLoadZip("/code/gen/batchGenCode?tables=" + tableNames, "ruoyi");
+        this.$download.zip("/code/gen/batchGenCode?tables=" + tableNames, "ruoyi");
       }
     },
     /** 同步数据库操作 */

--
Gitblit v1.9.3