Browse Source

http请求类,新增对上传文件的支持

niuheng 3 years ago
parent
commit
e4260d88b4

+ 0 - 1
src/components/systemGraph/index.vue

@@ -60,7 +60,6 @@
 </template>
 <script>
 import { mapState } from "vuex";
-import { logicConfig } from "@/logicConfig";
 import { sysGraphController } from "@/controller/systemGraph/sysGraphController";
 
 export default {

+ 84 - 44
src/utils/http/basic/axiosUtils.ts

@@ -37,7 +37,7 @@ axiosservice.interceptors.response.use(
     return res;
   },
   function (err) {
-    console.log("axios interceptors err = ", err);
+    console.error("axios interceptors err = ", err);
     return Promise.reject(err);
   }
 );
@@ -134,55 +134,80 @@ export class axiosUtils {
     }
   }
 
+
   /**
    * 上传文件
-   * fileServiceUrl 文件服务地址
-   * files 数组或者object,示例
+   * @param _paramobj 格式如下:
    * {
+   *    fileServiceUrl 文件服务地址
+   *    uploadProgressCall 上传进度回调函数,函数参数为object,格式如下:{fileName:'文件名称',uploadedTotal:1},uploadedTotal某个文件总共上传的字节数
+   *    oneUploadedCall 每上传完一个后的回调函数,函数参数为object,格式如下:{fileName:'文件名称',fileId:'文件ID'}
    *    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]
+   *    files 数组或者object,示例
+   *    { 
+   *      groupCode:'不传时,默认会取vuex中selectProject.groupCode',
+   *      projectId:'不传时,默认会取vuex中selectProject.id',
+   *      fileName:'文件名称',
+   *      fileBucket:'存储空间名称,可以不传',
+   *      file:文件信息,假设有一个input type为file id为txtFile的标签,那么file为document.getElementById('txtFile').files[0]
+   *    }
    * }
+   * @returns 
    */
-  protected async uploadFiles(fileServiceUrl: string, files: any) {
+  protected async uploadFiles(_paramobj: any) {
+    //注意,这里的this 指向的是实例化的子类
     var _this = this;
+    let userId = _paramobj.userId || vueStore.state.user.id;
+    let fileServiceUrl = _paramobj.fileServiceUrl;
+    let files = _paramobj.files;
     try {
-      return await start();
+      let waitFiles = files instanceof Array == true ? files : [files];
+      //上传成功的文件数量
+      let uploadedCount = 0;
+
+      for (let i = 0; i < waitFiles.length; i++) {
+        let _currFileObj = waitFiles[i];
+
+        //获取文件md5
+        let fileContentMd5 = await getFileContentMd5(_currFileObj);
+        //获取文件上传地址
+        let getUploadResult = await getUploadUrl(fileContentMd5 as string, _currFileObj);
+        switch (getUploadResult.result) {
+          case logicConfig.resultObj.success:
+            let getUploadData = getUploadResult.data || {};
+            //uploadCode 200 代表已经上传过了;    201  代表需上传
+            switch (getUploadData.uploadCode) { 
+              case 201:
+                //获取文件地址上传成功时进行上传
+                let uploadUrl = ((getUploadData.content || [])[0] || {}).uploadUrl;
+                if (!uploadUrl)
+                  return toolUtils.resultConstructor(logicConfig.resultObj.failure, null, '未获取到文件' + _currFileObj.fileName + '的上传地址');
+                //开始上传
+                await upload(uploadUrl, _currFileObj.file, function (progressObj) {
+                  if (typeof _paramobj.uploadProgressCall == 'function') {
+                    let uploadedFileSize = progressObj.loaded / progressObj.total * _currFileObj.file.size;
+                    _paramobj.uploadProgressCall({ uploadedTotal: uploadedFileSize, fileName: _currFileObj.fileName });
+                  }
+                });
+              case 200:
+                ++uploadedCount;
+                if (typeof _paramobj.oneUploadedCall == 'function') {
+                  _paramobj.oneUploadedCall({ fileName: _currFileObj.fileName, fileId: getUploadData.id });
+                }
+                break;
+            }
+            break;
+          default:
+            return toolUtils.resultConstructor(logicConfig.resultObj.failure, null, '获取文件' + _currFileObj.fileName + '的上传地址时出错:' + getUploadResult.message);
+        }
+        if (uploadedCount == waitFiles.length)
+          return toolUtils.resultConstructor(logicConfig.resultObj.success, null, null);
+      }
     } 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) => {
@@ -225,10 +250,11 @@ export class axiosUtils {
     };
 
     //获取文件上传地址
-    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;
+    async function getUploadUrl(fileContentMd5: string, _fileObj: any) {
+      let fileName = _fileObj.fileName;
+      let fileSize = _fileObj.file.size;
+      let projectId = _fileObj.projectId || vueStore.state.selectProject.id;
+      let groupCode = _fileObj.groupCode || vueStore.state.selectProject.groupCode;
       //应用ID暂时用不上
       let appId = '';
 
@@ -238,11 +264,25 @@ export class axiosUtils {
       let paramObj = {
         fileMd5: fileContentMd5,
         fileName: fileName,
-        //fileBucket
+        fileBucket: (window as any).__systemConf.baseRouteUrl,
         fileSize: fileSize
       };
-
-      return await _this.postRequest(getUploadUrl, paramObj);
+      return await _this.customRequest(getUploadUrl, null, paramObj, 'post');
     };
+
+    //上传
+    async function upload(uploadUrl, file, uploadProgressCall) {
+      return new Promise((resolve, reject) => {
+        var formData = new FormData();
+        formData.append('file', file);
+        axios.put(uploadUrl, formData, {
+          onUploadProgress: uploadProgressCall
+        }).then(function (res) {
+          resolve(res);
+        }).catch(function (error) {
+          reject(error);
+        });
+      });
+    }
   };
 }

+ 14 - 8
src/utils/http/basic/httpUtils.ts

@@ -65,17 +65,23 @@ export class httpUtils extends axiosUtils {
 
   /**
    * 上传文件
-   * files 数组或者object,示例
+   * @param _paramobj 格式如下:
    * {
+   *    uploadProgressCall 上传进度回调函数,函数参数为object,格式如下:{uploadedTotal:1},uploadedTotal总共上传了多少字节,是所有文件上传的字节数总和
+   *    oneUploadedCall 每上传完一个后的回调函数,函数参数为object,格式如下:{fileName:'文件名称'}
    *    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]
+   *    files 数组或者object,示例
+   *    { 
+   *      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);
+  public async uploadFiles(_paramobj: any) {
+    _paramobj.fileServiceUrl = this.baseUrl;
+    return await super.uploadFiles(_paramobj);
   }
 }

+ 12 - 0
src/utils/http/fileHttpUtils.ts

@@ -0,0 +1,12 @@
+/**
+ * 文件访问的http辅助类,供业务调用
+ * nh 2022.01.18
+ */
+
+import { httpUtils } from "./basic/httpUtils";
+
+export class fileHttpUtils extends httpUtils {
+    constructor() {
+        super((window as any).__systemConf.fileServiceUrl);
+    };
+}