소스 검색

新增通用方法简化下载使用

RuoYi 4 년 전
부모
커밋
7fcb1b2e0a

+ 1 - 0
ruoyi-common/ruoyi-common-core/src/main/java/com/ruoyi/common/core/utils/file/FileUtils.java

@@ -244,6 +244,7 @@ public class FileUtils
244 244
                 .append(percentEncodedFileName);
245 245
 
246 246
         response.setHeader("Content-disposition", contentDispositionValue.toString());
247
+        response.setHeader("download-filename", percentEncodedFileName);
247 248
     }
248 249
 
249 250
     /**

+ 24 - 0
ruoyi-ui/src/plugins/download.js

@@ -0,0 +1,24 @@
1
+import { saveAs } from 'file-saver'
2
+import axios from 'axios'
3
+import { getToken } from '@/utils/auth'
4
+
5
+const baseURL = process.env.VUE_APP_BASE_API
6
+
7
+export default {
8
+  zip(url, name) {
9
+    var url = baseURL + url
10
+    axios({
11
+      method: 'get',
12
+      url: url,
13
+      responseType: 'blob',
14
+      headers: { 'Authorization': 'Bearer ' + getToken() }
15
+    }).then(res => {
16
+      const blob = new Blob([res.data], { type: 'application/zip' })
17
+      this.saveAs(blob, name)
18
+    })
19
+  },
20
+  saveAs(text, name, opts) {
21
+    saveAs(text, name, opts);
22
+  }
23
+}
24
+

+ 3 - 0
ruoyi-ui/src/plugins/index.js

@@ -1,5 +1,6 @@
1 1
 import cache from './cache'
2 2
 import modal from './modal'
3
+import download from './download'
3 4
 
4 5
 export default {
5 6
   install(Vue) {
@@ -7,5 +8,7 @@ export default {
7 8
     Vue.prototype.$cache = cache
8 9
     // 模态框对象
9 10
     Vue.prototype.$modal = modal
11
+    // 下载文件
12
+    Vue.prototype.$download = download
10 13
   }
11 14
 }

+ 12 - 20
ruoyi-ui/src/utils/request.js

@@ -1,11 +1,14 @@
1 1
 import axios from 'axios'
2
-import { Notification, MessageBox, Message } from 'element-ui'
2
+import { Notification, MessageBox, Message, Loading } from 'element-ui'
3 3
 import store from '@/store'
4 4
 import { getToken } from '@/utils/auth'
5 5
 import errorCode from '@/utils/errorCode'
6 6
 import { tansParams } from "@/utils/ruoyi";
7
+import { saveAs } from 'file-saver'
7 8
 
8
-axios.defaults.headers['Content-Type'] = 'application/json;charset=utf-8'
9
+let downloadLoadingInstance;
10
+
11
+axios.defaults.headers['Conntent-Type'] = 'application/json;charset=utf-8'
9 12
 // 创建axios实例
10 13
 const service = axios.create({
11 14
   // axios中请求配置有baseURL选项,表示请求URL公共部分
@@ -90,31 +93,20 @@ service.interceptors.response.use(res => {
90 93
 
91 94
 // 通用下载方法
92 95
 export function download(url, params, filename) {
96
+  downloadLoadingInstance = Loading.service({ text: "正在下载数据,请稍后", spinner: "el-icon-loading", background: "rgba(0, 0, 0, 0.7)", })
93 97
   return service.post(url, params, {
94
-    transformRequest: [(params) => {
95
-      return tansParams(params)
96
-    }],
97
-    headers: {
98
-        'Content-Type': 'application/x-www-form-urlencoded'
99
-    },
98
+    transformRequest: [(params) => { return tansParams(params) }],
99
+    headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
100 100
     responseType: 'blob'
101 101
   }).then((data) => {
102 102
     const content = data
103 103
     const blob = new Blob([content])
104
-    if ('download' in document.createElement('a')) {
105
-      const elink = document.createElement('a')
106
-      elink.download = filename
107
-      elink.style.display = 'none'
108
-      elink.href = URL.createObjectURL(blob)
109
-      document.body.appendChild(elink)
110
-      elink.click()
111
-      URL.revokeObjectURL(elink.href)
112
-      document.body.removeChild(elink)
113
-    } else {
114
-      navigator.msSaveBlob(blob, filename)
115
-    }
104
+    saveAs(blob, filename)
105
+    downloadLoadingInstance.close();
116 106
   }).catch((r) => {
117 107
     console.error(r)
108
+    Message.error('下载文件出现错误,请联系管理员!')
109
+    downloadLoadingInstance.close();
118 110
   })
119 111
 }
120 112
 

+ 0 - 42
ruoyi-ui/src/utils/zipdownload.js

@@ -1,42 +0,0 @@
1
-import axios from 'axios'
2
-import { getToken } from '@/utils/auth'
3
-
4
-const mimeMap = {
5
-  xlsx: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
6
-  zip: 'application/zip'
7
-}
8
-
9
-const baseUrl = process.env.VUE_APP_BASE_API
10
-export function downLoadZip(str, filename) {
11
-  var url = baseUrl + str
12
-  axios({
13
-    method: 'get',
14
-    url: url,
15
-    responseType: 'blob',
16
-    headers: { 'Authorization': 'Bearer ' + getToken() }
17
-  }).then(res => {
18
-    resolveBlob(res, mimeMap.zip)
19
-  })
20
-}
21
-/**
22
- * 解析blob响应内容并下载
23
- * @param {*} res blob响应内容
24
- * @param {String} mimeType MIME类型
25
- */
26
-export function resolveBlob(res, mimeType) {
27
-  const aLink = document.createElement('a')
28
-  var blob = new Blob([res.data], { type: mimeType })
29
-  // //从response的headers中获取filename, 后端response.setHeader("Content-disposition", "attachment; filename=xxxx.docx") 设置的文件名;
30
-  var patt = new RegExp('filename=([^;]+\\.[^\\.;]+);*')
31
-  var contentDisposition = decodeURI(res.headers['content-disposition'])
32
-  var result = patt.exec(contentDisposition)
33
-  var fileName = result[1]
34
-  fileName = fileName.replace(/\"/g, '')
35
-  aLink.style.display = 'none'
36
-  aLink.href = URL.createObjectURL(blob)
37
-  aLink.setAttribute('download', fileName) // 设置下载文件名称
38
-  document.body.appendChild(aLink)
39
-  aLink.click()
40
-  URL.revokeObjectURL(aLink.href);//清除引用
41
-  document.body.removeChild(aLink);
42
-}

+ 4 - 15
ruoyi-ui/src/views/tool/build/index.vue

@@ -137,23 +137,13 @@
137 137
 
138 138
 <script>
139 139
 import draggable from 'vuedraggable'
140
-import { saveAs } from 'file-saver'
141 140
 import beautifier from 'js-beautify'
142 141
 import ClipboardJS from 'clipboard'
143 142
 import render from '@/utils/generator/render'
144 143
 import RightPanel from './RightPanel'
145
-import {
146
-  inputComponents,
147
-  selectComponents,
148
-  layoutComponents,
149
-  formConf
150
-} from '@/utils/generator/config'
151
-import {
152
-  exportDefault, beautifierConf, isNumberStr, titleCase
153
-} from '@/utils/index'
154
-import {
155
-  makeUpHtml, vueTemplate, vueScript, cssStyle
156
-} from '@/utils/generator/html'
144
+import { inputComponents, selectComponents, layoutComponents, formConf } from '@/utils/generator/config'
145
+import { beautifierConf, titleCase } from '@/utils/index'
146
+import { makeUpHtml, vueTemplate, vueScript, cssStyle } from '@/utils/generator/html'
157 147
 import { makeUpJs } from '@/utils/generator/js'
158 148
 import { makeUpCss } from '@/utils/generator/css'
159 149
 import drawingDefalut from '@/utils/generator/drawingDefalut'
@@ -161,7 +151,6 @@ import logo from '@/assets/logo/logo.png'
161 151
 import CodeTypeDialog from './CodeTypeDialog'
162 152
 import DraggableItem from './DraggableItem'
163 153
 
164
-const emptyActiveData = { style: {}, autosize: {} }
165 154
 let oldActiveId
166 155
 let tempActiveData
167 156
 
@@ -287,7 +276,7 @@ export default {
287 276
     execDownload(data) {
288 277
       const codeStr = this.generateCode()
289 278
       const blob = new Blob([codeStr], { type: 'text/plain;charset=utf-8' })
290
-      saveAs(blob, data.fileName)
279
+      this.$download.saveAs(blob, data.fileName)
291 280
     },
292 281
     execCopy(data) {
293 282
       document.getElementById('copyNode').click()

+ 1 - 2
ruoyi-ui/src/views/tool/gen/index.vue

@@ -180,7 +180,6 @@
180 180
 <script>
181 181
 import { listTable, previewTable, delTable, genCode, synchDb } from "@/api/tool/gen";
182 182
 import importTable from "./importTable";
183
-import { downLoadZip } from "@/utils/zipdownload";
184 183
 import hljs from "highlight.js/lib/highlight";
185 184
 import "highlight.js/styles/github-gist.css";
186 185
 hljs.registerLanguage("java", require("highlight.js/lib/languages/java"));
@@ -270,7 +269,7 @@ export default {
270 269
           this.$modal.msgSuccess("成功生成到自定义路径:" + row.genPath);
271 270
         });
272 271
       } else {
273
-        downLoadZip("/code/gen/batchGenCode?tables=" + tableNames, "ruoyi");
272
+        this.$download.zip("/code/gen/batchGenCode?tables=" + tableNames, "ruoyi");
274 273
       }
275 274
     },
276 275
     /** 同步数据库操作 */