Browse Source

添加oss上传

lex 1 year ago
parent
commit
ad0f221707

File diff suppressed because it is too large
+ 13744 - 1
package-lock.json


+ 1 - 0
package.json

@@ -12,6 +12,7 @@
   "dependencies": {
     "axios": "^0.18.0",
     "clean-deep": "^3.4.0",
+    "cos-js-sdk-v5": "^1.4.20",
     "dayjs": "^1.11.2",
     "echarts": "^4.2.0-rc.2",
     "element-ui": "^2.3.7",

+ 59 - 24
src/components/Tinymce/components/editorImage.vue

@@ -15,12 +15,12 @@
         class="editor-slide-upload"
         :action="ossUploadUrl"
         :data="dataObj"
-        :multiple="true"
+        :multiple="false"
         :file-list="fileList"
         :show-file-list="true"
         list-type="picture-card"
         :on-remove="handleRemove"
-        :on-success="handleSuccess"
+        :http-request="handleSuccess"
         :before-upload="beforeUpload"
       >
         <el-button size="small" type="primary">点击上传</el-button>
@@ -33,7 +33,7 @@
 
 <script>
 import { policy } from "@/api/oss";
-
+import { getUploadSign, onOnlyFileUpload } from "@/utils/oss-file-upload";
 export default {
   name: "editorSlideUpload",
   props: {
@@ -88,19 +88,34 @@ export default {
       this.fileList = [];
       this.dialogVisible = false;
     },
-    handleSuccess(response, file) {
-      const uid = file.uid;
+    async handleSuccess(info) {
+      // const uid = file.uid;
 
-      const objKeyArr = Object.keys(this.listObj);
-      console.log(objKeyArr, "objKeyArr", this.listObj);
-      for (let i = 0, len = objKeyArr.length; i < len; i++) {
-        if (this.listObj[objKeyArr[i]].uid === uid) {
-          this.listObj[objKeyArr[i]].url =
-            this.ossUploadUrl + "/" + this.listObj[objKeyArr[i]].key;
-          this.listObj[objKeyArr[i]].hasSuccess = true;
-          return;
-        }
+      try {
+        const objInfo = {
+          policy: info.data.policy,
+          signature: info.data.signature,
+          key: info.data.key,
+          KSSAccessKeyId: info.data.kssAccessKeyId,
+          acl: "public-read",
+          name: info.data.key,
+          file: info.file
+        };
+        console.log(objInfo, 'objInfo')
+        const uploadUrl = await onOnlyFileUpload(this.ossUploadUrl, objInfo)
+        this.listObj[info.file.uid].url = uploadUrl;
+        this.listObj[info.file.uid].hasSuccess = true;
+      } catch (err) {
+        console.log(err, 'err')
       }
+      // for (let i = 0, len = objKeyArr.length; i < len; i++) {
+      //   if (this.listObj[objKeyArr[i]].uid === uid) {
+      //     this.listObj[objKeyArr[i]].url =
+      //       this.ossUploadUrl + "/" + this.listObj[objKeyArr[i]].key;
+      //     this.listObj[objKeyArr[i]].hasSuccess = true;
+      //     return;
+      //   }
+      // }
     },
     handleRemove(file) {
       const uid = file.uid;
@@ -118,34 +133,54 @@ export default {
       const fileName = file.uid;
       this.listObj[fileName] = {};
       return new Promise((resolve, reject) => {
-        let key = new Date().getTime() + file.name;
+        let key = 'gym/' + new Date().getTime() + file.name;
         let obj = {
-          filename: file.name,
+          filename: key,
           bucketName: this.bucket_name,
           postData: {
-            filename: file.name,
+            filename: key,
             acl: "public-read",
-            key: key,
-            unknowValueField: [],
+            key: key
           },
         };
-        policy(obj)
-          .then((response) => {
+        // policy(obj)
+        //   .then((response) => {
+        //     _self.dataObj.policy = response.data.policy;
+        //     _self.dataObj.signature = response.data.signature;
+        //     _self.dataObj.KSSAccessKeyId = response.data.kssAccessKeyId;
+        //     _self.dataObj.key = key;
+        //     _self.dataObj.name = file.name;
+        //     _self.dataObj.acl = "public-read";
+        //     _self.listObj[fileName] = {
+        //       hasSuccess: false,
+        //       uid: file.uid,
+        //       width: this.width,
+        //       height: this.height,
+        //       name: file.name,
+        //       key: key,
+        //     };
+
+        //     resolve(true);
+        //   })
+        //   .catch((err) => {
+        //     console.log(err);
+        //     reject(false);
+        //   });
+        getUploadSign(obj).then(response => {
             _self.dataObj.policy = response.data.policy;
             _self.dataObj.signature = response.data.signature;
             _self.dataObj.KSSAccessKeyId = response.data.kssAccessKeyId;
             _self.dataObj.key = key;
-            _self.dataObj.name = file.name;
+            _self.dataObj.name = key;
             _self.dataObj.acl = "public-read";
             _self.listObj[fileName] = {
               hasSuccess: false,
               uid: file.uid,
               width: this.width,
               height: this.height,
-              name: file.name,
+              name: key,
               key: key,
             };
-
             resolve(true);
           })
           .catch((err) => {

+ 29 - 15
src/components/Upload/multiUpload.vue

@@ -9,7 +9,7 @@
       :file-list="fileList"
       :before-upload="beforeUpload"
       :on-remove="handleRemove"
-      :on-success="handleUploadSuccess"
+      :http-request="handleUploadSuccess"
       :on-preview="handlePreview"
       :limit="maxCount"
       :on-exceed="handleExceed"
@@ -23,7 +23,7 @@
 </template>
 <script>
 import { policy } from "@/api/oss";
-
+import { getUploadSign, onOnlyFileUpload } from "@/utils/oss-file-upload";
 export default {
   name: "multiUpload",
   props: {
@@ -101,19 +101,16 @@ export default {
           postData: {
             filename: file.name,
             acl: "public-read",
-            key: key,
-            unknowValueField: [],
+            key: key
           },
         };
-        policy(obj)
-          .then((response) => {
+          getUploadSign(obj).then(response => {
             _self.dataObj.policy = response.data.policy;
             _self.dataObj.signature = response.data.signature;
             _self.dataObj.KSSAccessKeyId = response.data.kssAccessKeyId;
             _self.dataObj.key = key;
-            _self.dataObj.name = file.name;
+            _self.dataObj.name = key;
             _self.dataObj.acl = "public-read";
-
             var ks3Options = {
               KSSAccessKeyId: response.data.kssAccessKeyId,
               policy: response.data.policy,
@@ -136,14 +133,31 @@ export default {
           });
       });
     },
-    handleUploadSuccess(res, file) {
-      let url = this.ossUploadUrl + "/" + this.dataObj.key;
-      if (!this.useOss) {
-        //不使用oss直接获取图片路径
-        url = res.data.url;
+    async handleUploadSuccess(info, file) {
+      // let url = this.ossUploadUrl + "/" + this.dataObj.key;
+      // if (!this.useOss) {
+      //   //不使用oss直接获取图片路径
+      //   url = res.data.url;
+      // }
+      // this.fileList.push({ name: file.name, url: url });
+      // this.emitInput(this.fileList);
+      try {
+        const objInfo = {
+          policy: info.data.policy,
+          signature: info.data.signature,
+          key: info.data.key,
+          KSSAccessKeyId: info.data.kssAccessKeyId,
+          acl: "public-read",
+          name: info.data.key,
+          file: info.file
+        };
+        console.log(objInfo, 'objInfo')
+        const uploadUrl = await onOnlyFileUpload(this.ossUploadUrl, objInfo)
+        this.fileList.push({ name: info.file.name, url: uploadUrl });
+        this.emitInput(this.fileList);
+      } catch (err) {
+        console.log(err, 'err')
       }
-      this.fileList.push({ name: file.name, url: url });
-      this.emitInput(this.fileList);
     },
     handleExceed(files, fileList) {
       this.$message({

+ 24 - 16
src/components/Upload/singleUpload.vue

@@ -11,7 +11,7 @@
       :file-list="fileList"
       :before-upload="beforeUpload"
       :on-remove="handleRemove"
-      :on-success="handleUploadSuccess"
+      :http-request="handleUploadSuccess"
       :on-preview="handlePreview"
     >
       <el-button size="small" type="primary">点击上传</el-button>
@@ -26,6 +26,7 @@
 </template>
 <script>
 import { policy } from "@/api/oss";
+import { getUploadSign, onOnlyFileUpload } from "@/utils/oss-file-upload";
 export default {
   name: "singleUpload",
   props: {
@@ -117,18 +118,13 @@ export default {
           },
         };
 
-        policy(obj)
-          .then((response) => {
+          getUploadSign(obj).then(response => {
             _self.dataObj.policy = response.data.policy;
             _self.dataObj.signature = response.data.signature;
             _self.dataObj.KSSAccessKeyId = response.data.kssAccessKeyId;
             _self.dataObj.key = key;
-            _self.dataObj.name = file.name;
+            _self.dataObj.name = key;
             _self.dataObj.acl = "public-read";
-
-            // _self.dataObj.host = response.data.host;
-            // _self.dataObj.callback = response.data.callback;
-
             var ks3Options = {
               KSSAccessKeyId: response.data.kssAccessKeyId,
               policy: response.data.policy,
@@ -145,7 +141,6 @@ export default {
               drop_element: document.body,
             };
             var tempUpload = new ks3FileUploader(ks3Options);
-            //  tempUpload.uploader.start()
             resolve(true);
           })
           .catch((err) => {
@@ -154,16 +149,29 @@ export default {
           });
       });
     },
-    handleUploadSuccess(res, file) {
-      let url = this.ossUploadUrl + "/" + this.dataObj.key;
+    async handleUploadSuccess(info) {
+      console.log(info, 'info')
+      try {
+        const objInfo = {
+          policy: info.data.policy,
+          signature: info.data.signature,
+          key: info.data.key,
+          KSSAccessKeyId: info.data.kssAccessKeyId,
+          acl: "public-read",
+          name: info.data.key,
+          file: info.file
+        };
+        console.log(objInfo, 'objInfo')
+        const uploadUrl = await onOnlyFileUpload(this.ossUploadUrl, objInfo)
+
       this.showFileList = true;
       this.fileList.pop();
-      if (!this.useOss) {
-        //不使用oss直接获取图片路径
-        url = res.data.url;
+      this.fileList.push({ name: info.file.name, url: uploadUrl });
+      this.emitInput(uploadUrl);
+      } catch (err) {
+        console.log(err, 'err')
       }
-      this.fileList.push({ name: file.name, url: url });
-      this.emitInput(this.fileList[0].url);
+
     },
   },
 };

+ 219 - 0
src/utils/oss-file-upload.js

@@ -0,0 +1,219 @@
+import request from "./request";
+import axios from "axios";
+// import umiRequest from "umi-request";
+import COS from "cos-js-sdk-v5";
+export const ossSwitch = "tencent"; //as 'ks3' | 'tencent'; // 上传文件服务商
+const tencentBucket = "daya-online-1303457149";
+
+/**
+ * 管乐团 gyt/
+ * 酷乐秀 klx/
+ * 课堂乐器 ktqy/
+ * 管乐迷 gym/
+ */
+
+// 定义一个cos 对象
+/**
+ * 获取上传文件签名
+ * @param params 上传对应参数
+ * { filename: fileName,
+     bucketName: props.bucketName,
+     postData: {
+      filename: fileName,
+      acl: 'public-read',
+      key: fileName,
+      unknowValueField: []
+    }}
+ * @param oss 服务商 ks3 tencent
+ * @returns ”{'signatur'':'',''kssAccessKeyI'':'',''policy': '' }“
+ */
+export const getUploadSign = async params => {
+  const { bucketName, filename, postData } = params;
+  const ossType = ossSwitch;
+  let bucket = bucketName;
+  let file = filename;
+  // const key = postData.key;
+  let tempPostData = {};
+  if (ossType === "tencent") {
+    bucket = tencentBucket;
+    file = "gym/" + filename;
+
+    tempPostData = {
+      key: "gym/" + postData.key
+    };
+  } else {
+    tempPostData = postData;
+  }
+  return request.post("/api-web/getUploadSign?pluginName=" + ossType, {
+    postData: tempPostData,
+    pluginName: ossType,
+    bucketName: bucket,
+    filename: file
+  });
+};
+
+/**
+ * 使用组件上传时,调用方法
+ * @param param0
+ */
+export const onFileUpload = ({
+  file,
+  action,
+  data,
+  onProgress,
+  onFinish,
+  onError
+}) => {
+  if (ossSwitch === "ks3") {
+    const fileParams = {
+      policy: data.policy,
+      signature: data.signature,
+      key: data.key,
+      acl: "public-read",
+      KSSAccessKeyId: data.KSSAccessKeyId,
+      name: data.name
+    };
+    const formData = new FormData();
+    for (const key in fileParams) {
+      formData.append(key, fileParams[key]);
+    }
+    formData.append("file", data.file);
+    axios
+      .post(action, formData, {
+        onUploadProgress: ({ progress }) => {
+          onProgress({ percent: Math.ceil((progress || 0) * 100) });
+        }
+      })
+      .then(() => {
+        file.url = action + data.key;
+        onFinish();
+      })
+      .catch(error => {
+        onError(error);
+      });
+  } else {
+    const cos = new COS({
+      Domain: "https://oss.dayaedu.com",
+      Protocol: "https",
+      // getAuthorization 必选参数
+      getAuthorization: async (options, callback) => {
+        callback({ Authorization: data.signature });
+      }
+    });
+    cos
+      .uploadFile({
+        Bucket: tencentBucket /* 填写自己的 bucket,必须字段 */,
+        Region: "ap-nanjing" /* 存储桶所在地域,必须字段 */,
+        Key: `gym/${data.name}`,
+        /* 存储在桶里的对象键(例如:1.jpg,a/b/test.txt,图片.jpg)支持中文,必须字段 */
+        Body: data.file.file, // 上传文件对象
+        SliceSize:
+          1024 *
+          1024 *
+          500 /* 触发分块上传的阈值,超过5MB使用分块上传,小于5MB使用简单上传。可自行设置,非必须 */,
+        onProgress: function(progressData) {
+          onProgress({ percent: Math.ceil((progressData.percent || 0) * 100) });
+        }
+      })
+      .then(res => {
+        // file.url = 'https://' + res.Location;
+        if (res.Location && res.Location.indexOf("http") >= 0) {
+          file.url = res.Location;
+        } else {
+          file.url = "https://" + res.Location;
+        }
+        onFinish();
+      })
+      .catch(() => {
+        onError();
+      });
+  }
+};
+
+export const onOnlyFileUpload = async (action, params) => {
+  if (ossSwitch === "ks3") {
+    const fileParams = {
+      policy: params.policy,
+      signature: params.signature,
+      key: params.key,
+      acl: "public-read",
+      KSSAccessKeyId: params.KSSAccessKeyId,
+      name: params.name
+    };
+    const formData = new FormData();
+    for (const key in fileParams) {
+      formData.append(key, fileParams[key]);
+    }
+    formData.append("file", params.file);
+    let file = "";
+    let errorObj = null;
+    await axios
+      .post(action, formData, {
+        // onUploadProgress: ({ progress }) => {
+        //   console.log(progress);
+        //   onProgress({ percent: Math.ceil((progress || 0) * 100) });
+        // }
+      })
+      .then(() => {
+        file = action + params.key;
+      })
+      .catch(error => {
+        // onError(error);
+        errorObj = error;
+        // throw new Error(error);
+      });
+    if (file) {
+      return file;
+    } else {
+      throw new Error(errorObj);
+    }
+  } else {
+    let file = "";
+    let errorObj = null;
+    // console.log(params, "params");
+    const cos = new COS({
+      Domain: "https://oss.dayaedu.com",
+      // getAuthorization 必选参数
+      getAuthorization: async (options, callback) => {
+        callback({ Authorization: params.signature });
+      }
+    });
+
+    await cos
+      .uploadFile({
+        Bucket: tencentBucket /* 填写自己的 bucket,必须字段 */,
+        Region: "ap-nanjing" /* 存储桶所在地域,必须字段 */,
+        Key: `gym/${params.name}`,
+        /* 存储在桶里的对象键(例如:1.jpg,a/b/test.txt,图片.jpg)支持中文,必须字段 */
+        Body: params.file, // 上传文件对象
+        SliceSize:
+          1024 *
+          1024 *
+          500 /* 触发分块上传的阈值,超过5MB使用分块上传,小于5MB使用简单上传。可自行设置,非必须 */
+        // onProgress: function (progressData) {
+        //   onProgress({ percent: Math.ceil((progressData.percent || 0) * 100) });
+        // }
+      })
+      .then(res => {
+        // file.url = 'https://' + res.Location;
+        // file = 'https://' + res.Location;
+        if (res.Location && res.Location.indexOf("http") >= 0) {
+          file = res.Location;
+        } else {
+          file = "https://" + res.Location;
+        }
+        // onFinish();
+      })
+      .catch(error => {
+        // console.log(error, 'error');
+        // onError();
+        // throw new Error(error);
+        errorObj = error;
+      });
+    if (file) {
+      return file;
+    } else {
+      throw new Error(errorObj);
+    }
+  }
+};

Some files were not shown because too many files changed in this diff