Преглед изворни кода

1、服务配置改成完整的http地址
2、axiosUtils.ts、httpUtils.ts新增上传方法

niuheng пре 3 година
родитељ
комит
ebe6259211
5 измењених фајлова са 164 додато и 13 уклоњено
  1. 3 2
      package.json
  2. 2 2
      public/systemConf.js
  3. 117 9
      src/utils/http/basic/axiosUtils.ts
  4. 16 0
      src/utils/http/basic/httpUtils.ts
  5. 26 0
      src/utils/toolUtils.ts

+ 3 - 2
package.json

@@ -15,11 +15,12 @@
     "@saga-web/graph": "^2.1.139",
     "font-awesome": "^4.7.0",
     "handsontable-pro": "^3.0.0",
+    "jquery": "^3.3.1",
     "meri-design": "^1.5.515",
     "moment": "^2.29.1",
+    "spark-md5": "^3.0.2",
     "vue-router": "^3.5.3",
-    "vuex": "^3.6.2",
-    "jquery": "^3.3.1"
+    "vuex": "^3.6.2"
   },
   "devDependencies": {
     "@vue/cli-plugin-babel": "~4.5.0",

+ 2 - 2
public/systemConf.js

@@ -6,9 +6,9 @@ var __systemConf = {
   //系统图服务域名
   sysGraphServiceUrl: 'http://develop.ysbdtp.com/adm-diagram',
   //登录服务域名
-  loginServiceUrl: '/loginRequest',
+  loginServiceUrl: 'http://develop.ysbdtp.com/adm-server',
   //文件服务域名
-  fileServiceUrl: 'http://develop.ysbdtp.com/adm-server',
+  fileServiceUrl: 'http://develop.ysbdtp.com/dmp-file',
   // 地图key
   mapKey: 'd42beb96e0e4fb0d49482975abeae1b7',
   //登录相关配置

+ 117 - 9
src/utils/http/basic/axiosUtils.ts

@@ -6,6 +6,8 @@
 import axios from "axios";
 import vueStore from "@/store";
 import { logicConfig } from "@/logicConfig";
+import { toolUtils } from "@/utils/toolUtils";
+import SparkMD5 from 'spark-md5';
 
 var CancelToken = axios.CancelToken;
 var cancel;
@@ -53,12 +55,9 @@ export class axiosUtils {
       var urlPrefix = urlArr[0];
       var urlParamStr = urlArr[1] || "";
 
-      var paramKeyArr = Object.keys(data || {});
-      paramKeyArr.forEach(_key => { 
-        urlParamStr = _key + '=' + data[_key] + '&' + urlParamStr;
-      });
+      var _newParamStr = toolUtils.objectKeyToUrlParam(data);
 
-      var newUrl = urlPrefix + '?' + urlParamStr;
+      var newUrl = urlPrefix + '?' + _newParamStr + '&' + urlParamStr;
 
       let response = await this.customRequest(newUrl, {}, {}, "get");
       return response;
@@ -131,10 +130,119 @@ export class axiosUtils {
     } catch (err) {
       // throw err;
       console.error(err);
-      return {
-        result: logicConfig.resultObj.failure,
-        message: '请求异常'
-      };
+      return toolUtils.resultConstructor(logicConfig.resultObj.failure, null, '请求异常,' + err.message);
     }
   }
+
+  /**
+   * 上传文件
+   * fileServiceUrl 文件服务地址
+   * files 数组或者object,示例
+   * {
+   *    userId:'不传时,默认会取vuex中user.id',
+   *    groupCode:'不传时,默认会取vuex中selectProject.groupCode',
+   *    projectId:'不传时,默认会取vuex中selectProject.id',
+   *    fileName:'文件名称',
+   *    fileBucket:'存储空间名称,可以不传',
+   *    file:文件信息,假设有一个input type为file id为txtFile的标签,那么file为document.getElementById('txtFile').files[0]
+   * }
+   */
+  protected async uploadFiles(fileServiceUrl: string, files: any) {
+    var _this = this;
+    try {
+      return await start();
+    } catch (error) {
+      console.error(error);
+      return toolUtils.resultConstructor(logicConfig.resultObj.failure, null, error.message);
+    }
+
+    function start() {
+      return new Promise((resolve, reject) => {
+        let waitFiles = files instanceof Array == true ? files : [files];
+        let uploadedCount = 0;
+
+        for (let i = 0; i < waitFiles.length; i++) {
+          let _currFileObj = waitFiles[i];
+
+          (async function (_fileObj, _fileIndex) {
+            try {
+              //获取文件md5
+              let fileContentMd5 = await getFileContentMd5(_fileObj);
+              console.log(fileContentMd5);
+              //获取文件上传地址
+              let getUploadResult = await getUploadUrl(fileContentMd5 as string, _fileObj.fileName, _fileObj.file.size);
+              console.log(getUploadResult);
+              resolve(waitFiles);
+            } catch (error) {
+              reject(error);
+            }
+          })(_currFileObj, i);
+
+        }
+      });
+
+    };
+
+    //获取文件内容的md5值
+    function getFileContentMd5(_fileObj) {
+      return new Promise((resolve, reject) => {
+        let file = _fileObj.file;
+        let blobSlice = File.prototype.slice;
+        let chunkSize = 2097152;
+        let chunks = Math.ceil(file.size / chunkSize);
+        let currentChunk = 0;
+        let spark = new SparkMD5.ArrayBuffer();
+        let fileReader = new FileReader();
+        fileReader.onload = function (e) {
+          spark.append(e.target.result);                   // Append array buffer
+          currentChunk++;
+          if (currentChunk < chunks) {
+            loadNext();
+          } else {
+            let fileContentMd5 = spark.end();
+            console.info('computed hash', fileContentMd5);  // Compute hash
+            //文件md5获取完成后,调用后台接口获取上传地址
+            // let getUploadResult = await getUploadUrl(fileContentMd5, _fileObj.fileName, file.size);
+            resolve(fileContentMd5);
+          }
+        };
+
+        fileReader.onerror = function (e) {
+          let errStr = '文件:' + _fileObj.fileName + '读取错误:';
+          console.error(e);
+          reject(errStr);
+        };
+
+        function loadNext() {
+          var start = currentChunk * chunkSize,
+            end = ((start + chunkSize) >= file.size) ? file.size : start + chunkSize;
+
+          fileReader.readAsArrayBuffer(blobSlice.call(file, start, end));
+        }
+
+        loadNext();
+      });
+    };
+
+    //获取文件上传地址
+    async function getUploadUrl(fileContentMd5: string, fileName: string, fileSize: number) {
+      let userId = vueStore.state.user.id;
+      let projectId = vueStore.state.selectProject.id;
+      let groupCode = vueStore.state.selectProject.groupCode;
+      //应用ID暂时用不上
+      let appId = '';
+
+      let getUploadUrl = toolUtils.getBaseHttpUrl(fileServiceUrl, 'file/initSingleUpload') +
+        '?userId=' + userId + '&projectId=' + projectId + '&groupCode=' + groupCode + '&appId=';
+
+      let paramObj = {
+        fileMd5: fileContentMd5,
+        fileName: fileName,
+        //fileBucket
+        fileSize: fileSize
+      };
+
+      return await _this.postRequest(getUploadUrl, paramObj);
+    };
+  };
 }

+ 16 - 0
src/utils/http/basic/httpUtils.ts

@@ -62,4 +62,20 @@ export class httpUtils extends axiosUtils {
   ) {
     return await super.customRequest(url, headers, data, method);
   }
+
+  /**
+   * 上传文件
+   * files 数组或者object,示例
+   * {
+   *    userId:'不传时,默认会取vuex中user.id',
+   *    groupCode:'不传时,默认会取vuex中selectProject.groupCode',
+   *    projectId:'不传时,默认会取vuex中selectProject.id',
+   *    fileName:'文件名称',
+   *    fileBucket:'存储空间名称,可以不传',
+   *    file:文件信息,假设有一个input type为file id为txtFile的标签,那么file为document.getElementById('txtFile').files[0]
+   * }
+   */
+  public async uploadFiles(files: any) {
+    return await super.uploadFiles(this.baseUrl, files);
+  }
 }

+ 26 - 0
src/utils/toolUtils.ts

@@ -74,4 +74,30 @@ export class toolUtils {
     }
     return newData;
   };
+
+  /**
+   * 把object对象中的属性转为url中的参数字符串。比如:{a:1,b:2}转为a=1&b=2
+   */
+  static objectKeyToUrlParam(_obj: any) {
+    var paramStr = '';
+    var keyArr = Object.keys(_obj || {});
+    keyArr.forEach((_key, _index) => {
+      paramStr = paramStr + _key + '=' + _obj[_key] + (_index == keyArr.length - 1 ? '' : '&');
+    });
+    return paramStr;
+  };
+
+  /**
+   * 拼装返回给页面的接口调用结果
+   * resultStr 结果字符串,成功时为success,否则为失败码
+   * data 数据
+   * reason 失败时的原因
+   */
+  static resultConstructor(resultStr, data, reason) {
+    return {
+      result: resultStr,
+      data: data,
+      message: reason
+    };
+  };
 }