huangyongcong il y a 1 an
Parent
commit
f8f65f00d2

+ 3 - 1
App.vue

@@ -11,7 +11,9 @@ export default {
   }
 }
 </script>
-
+<style>
+@import "./static/iconfont/iconfont.css";
+</style>
 <style lang="scss">
 /*每个页面公共css */
 @import '~@/css/uni.scss';

+ 5 - 0
api/student.js

@@ -0,0 +1,5 @@
+import request from "@/utils/request";
+
+export function cradToStudentInfo(data) {
+  return request.post('machine/student/cardToInfo', data)
+}

+ 3 - 0
main.js

@@ -3,6 +3,7 @@ import {createSSRApp} from 'vue'
 import * as Pinia from 'pinia'
 import uvUI from '@/uni_modules/uv-ui-tools'
 import bootstrap from './utils/bootstrap'
+import config from "@/utils/config";
 
 export function createApp() {
   const app = createSSRApp(App)
@@ -24,6 +25,8 @@ export function createApp() {
 
   bootstrap()
 
+  app.config.globalProperties.$imgUrl = config.get('imgUrl')
+
   return {
     app,
     Pinia,

+ 7 - 1
manifest.json

@@ -137,5 +137,11 @@
   "uniStatistics": {
     "enable": false
   },
-  "vueVersion": "3"
+  "vueVersion": "3",
+  "h5": {
+    "title": "BMI",
+    "devServer": {
+      "disableHostCheck": true
+    }
+  }
 }

+ 7 - 1
manifestTemp.json

@@ -137,5 +137,11 @@
   "uniStatistics": {
     "enable": false
   },
-  "vueVersion": "3"
+  "vueVersion": "3",
+  "h5": {
+    "title": "BMI",
+    "devServer": {
+      "disableHostCheck": true
+    }
+  }
 }

+ 27 - 25
package.json

@@ -1,27 +1,29 @@
 {
-	"uni-app": {
-		"scripts": {
-			"teacher-dev-h5": {
-				"title": "测试服 - H5",
-				"browser": "chrome",
-				"env": {
-					"IS_TEST": true,
-					"NODE_ENV": "development",
-					"UNI_PLATFORM": "h5"
-				}
-			},
-			"teacher-production-h5": {
-				"title": "正式服 - H5",
-				"browser": "chrome",
-				"env": {
-					"IS_TEST": false,
-					"NODE_ENV": "production",
-					"UNI_PLATFORM": "h5"
-				}
-			}
-		}
-	},
-	"devDependencies": {
-		"pinia": "^2.1.7"
-	}
+  "uni-app": {
+    "scripts": {
+      "teacher-dev-h5": {
+        "title": "机器 测试服 - H5",
+        "browser": "chrome",
+        "env": {
+          "UNI_PLATFORM": "h5"
+        },
+        "define": {
+          "IS_TEST": true
+        }
+      },
+      "teacher-production-h5": {
+        "title": "机器 正式服 - H5",
+        "browser": "chrome",
+        "env": {
+          "UNI_PLATFORM": "h5"
+        },
+        "define": {
+          "IS_TEST": false
+        }
+      }
+    }
+  },
+  "devDependencies": {
+    "pinia": "^2.1.7"
+  }
 }

+ 15 - 10
pages/index/index.vue

@@ -3,7 +3,7 @@
     <ly-back :showBack="false"/>
     <view class="search w100 h100 flex-center-center">
       <view class="btn btn-primary" @click="search">扫码</view>
-      <view class="btn btn-primary" @click="toSelect">手动选择</view>
+      <!--      <view class="btn btn-primary" @click="toSelect">手动选择</view>-->
     </view>
   </view>
 </template>
@@ -11,6 +11,8 @@
 <script setup>
 import {reactive} from "vue";
 import {navTo, showToast} from "@/utils/app";
+import {cradToStudentInfo} from "@/api/student";
+import storage from "@/utils/storage";
 
 const pD = reactive({
   title: '学生未激活',
@@ -20,17 +22,20 @@ const pD = reactive({
 const queryForm = reactive({
   student_id: 0,
 })
-const search = () => {
-  // queryForm.student_id = 2260
-}
-const selectHandle = (type) => {
-  if (type === 'up') {
-    type--
-    if (type < 0) type = 0
+const search = async () => {
+  const {code, msg, data} = await cradToStudentInfo({
+    mac: 'BBBBBBBBBBBB'
+  })
+  if (code === 1) {
+    queryForm.student_id = data.student.id
+    storage.setKey(`student-${data.student.id}`)
+    navTo('pages/task/info', {
+      id: queryForm.student_id,
+    })
   } else {
-    type++
-    if (type > pD.selectMax) type = 0
+    showToast(msg)
   }
+  // navTo('pages/task/info')
 }
 const toSelect = () => {
   navTo('pages/classes/select')

+ 97 - 35
pages/task/info.vue

@@ -1,63 +1,110 @@
 <template>
-  <view class="container">
-    <view v-if="queryForm.student_id<=0" class="search w100 h100 flex-center-center">
-      <view class="btn btn-primary" @click="search">扫码</view>
-      <view class="btn btn-primary" @click="toSelect">手动选择</view>
+  <view class="window-box dis-flex">
+    <ly-back :autoBack="false" @backClick="backClick"/>
+    <view v-if="countDown > 0" class="countDown">{{ formatZero(countDown, 2) }}</view>
+    <view class="window w40 flex-center-center flex-dir-column">
+      <student-info :student="student"/>
     </view>
-    <view v-if="queryForm.student_id>0" class="w100 h100 dis-flex">
-      <view class="window w40 flex-center-center flex-dir-column">
-        <uv-image/>
-        <view class="">{{ pD.title }}</view>
-      </view>
-      <view class="w60 h100 dis-flex flex-x-center flex-dir-column">
-        <view :class="{action:pD.select === 0}" class="info-item">
-          <view class="info-item-label">视力</view>
+    <view class="w60 h100 dis-flex flex-x-center flex-dir-column">
+      <template v-if="configStore.mType === 7">
+        <view class="info-item">
+          <view class="info-item-label">身高</view>
           <view class="">
-            <view class="btn btn-primary">进入视力</view>
+            <view class="col-checked f-64">{{ queryForm.value1 }}</view>
           </view>
         </view>
-        <view :class="{action:pD.select === 1}" class="info-item">
-          <view class="info-item-label">体重/身高</view>
+        <view class="info-item">
+          <view class="info-item-label">体重</view>
           <view class="">
-            {{}}
-            <view class="btn btn-primary">进入体重/身高</view>
+            <view class="col-checked f-64">{{ queryForm.value2 }}</view>
           </view>
         </view>
-        <view class="info-item">
-          <view class="btn btn-primary">下一个</view>
+      </template>
+      <view v-if="configStore.mType === 8" class="info-item">
+        <view class="info-item-label">肺活量</view>
+        <view class="">
+          <view class="btn btn-primary">进入肺活量</view>
         </view>
       </view>
+      <view v-if="configStore.mType === 9" class="info-item">
+        <view class="info-item-label">视力</view>
+        <view class="">
+          <view class="btn btn-primary">进入视力</view>
+        </view>
+      </view>
+      <!--      <view class="info-item" @click="toTask(10)">-->
+      <!--        <view class="btn btn-primary">进入测试</view>-->
+      <!--      </view>-->
     </view>
+    <ly-modal ref="modelRef"></ly-modal>
   </view>
 </template>
 
 <script setup>
-import {reactive} from "vue";
-import {navTo} from "@/utils/app";
+import {onActivated, onMounted, reactive, ref} from "vue";
+import {formatZero} from "@/utils/util";
+import {useConfigStore} from "@/store/useConfigStore";
+import {confirmModal, getBeforePage, navTo, redirectTo, showToast} from "@/utils/app";
+import debounce from "@/utils/debounce";
+import studentInfo from "./studentInfo"
+import storage from "@/utils/storage";
+
+const configStore = useConfigStore()
+const countDown = ref(0)
+const debounces = new debounce()
+const modelRef = ref()
 
-const pD = reactive({
-  title: '学生未激活',
-  select: 0,
-  selectMax: 1,
+let student = reactive({
+  jname: '未识别',
+  gender: 1,
 })
 const queryForm = reactive({
   student_id: 0,
+  value1: 0,
+  value2: 0,
 })
 const search = () => {
   queryForm.student_id = 2260
 }
-const selectHandle = (type) => {
-  if (type === 'up') {
-    type--
-    if (type < 0) type = 0
-  } else {
-    type++
-    if (type > pD.selectMax) type = 0
-  }
+const backClick = () => {
+  console.log('modelRef', modelRef, modelRef.value.open)
+  modelRef.value.open({
+    title: '温馨提示',
+    content: '确认要退出吗?',
+    showCancelButton: true,
+  })
+  // confirmModal('请认要退出吗?').then(() => {
+  //   redirectTo('pages/index/index')
+  // }, () => {
+  // })
+}
+const logout = () => {
+  storage.remove(`student-${student.id}`)
+  redirectTo('pages/index/index')
 }
-const toSelect = () => {
-  navTo('pages/classes/select')
+const countDownHandle = () => {
+  countDown.value = 30
+  debounces.countDown('countDown', {
+    duration: 30000,
+    callback: () => {
+      countDown.value--
+    },
+    endCallback: () => {
+      // 清空缓存学生信息
+      // logout()
+    },
+  })
 }
+
+// 挂载完成之后
+onMounted((r) => {
+  // student = storage.getKey(`student-${r.id}`)
+  countDownHandle()
+})
+
+// 激活页面时
+onActivated(() => {
+})
 </script>
 
 <style lang="scss" scoped>
@@ -78,4 +125,19 @@ const toSelect = () => {
     margin-right: 50rpx;
   }
 }
+
+.countDown {
+  width: 130rpx;
+  height: 130rpx;
+  position: fixed;
+  top: 20rpx;
+  right: 20rpx;
+  border: 6rpx solid green;
+  color: green;
+  border-radius: 50%;
+  display: flex;
+  justify-content: center;
+  align-items: center;
+  font-size: 60rpx;
+}
 </style>

+ 35 - 0
pages/task/studentInfo.vue

@@ -0,0 +1,35 @@
+<template>
+  <view class="">
+    <view class="window w40 flex-center-center flex-dir-column">
+      <uv-image :src="`${imgUrl}/avatar-${props.student.gender==2?'girl':'boy'}.png`"/>
+      <view class="">{{ props.student.jname || '' }}</view>
+    </view>
+  </view>
+</template>
+
+<script setup>
+import {onActivated, onMounted, reactive, ref} from "vue";
+import config from "@/utils/config";
+
+const props = defineProps({
+  student: {
+    type: [Object, Array],
+    default: () => {
+      return {
+        jname: '未识别',
+        gender: 1,
+      }
+    },
+  },
+})
+const countDown = ref(0)
+const imgUrl = config.get('imgUrl')
+
+// 挂载完成之后
+onMounted(() => {
+})
+</script>
+
+<style lang="scss" scoped>
+
+</style>

+ 18 - 10
plugins/ly-back.vue

@@ -1,7 +1,7 @@
 <template xmlns="">
   <view class="">
-    <view class="p-f back-box" @click="clickHandle">
-      <ly-icon :size="60" color="" name="icon-fanhui"/>
+    <view v-if="props.showBack" :class="{'action':select === 0}" class="p-f back-box" @click="clickHandle">
+      <ly-icon :color="color" :size="60" name="icon-fanhui"/>
     </view>
     <view class="p-f bottom-right"></view>
     <view class="p-f mac-info" @click="toSetting">
@@ -14,13 +14,14 @@
 import {reactive} from "vue";
 import {navigateBack, navTo, showToast} from "@/utils/app";
 import {useUserStore} from "@/store/useUserStore";
-import {useConfigStore} from "@/store/useConfigStore";
 import debounce from "@/utils/debounce";
 
-const configStore = useConfigStore()
+const debounces = new debounce()
+
 const userStore = useUserStore()
 
 const pd = reactive({})
+const emits = defineEmits(['backClick'])
 const props = defineProps({
   showBack: {
     type: Boolean,
@@ -32,23 +33,24 @@ const props = defineProps({
   },
   color: {
     type: String,
-    default: '#FFF'
+    default: '#000'
   },
-  backClick: {
-    type: Function,
+  select: {
+    type: [String, Number],
+    default: -1
   },
 })
 
 const clickHandle = () => {
-  if (this.autoBack) {
+  if (props.autoBack) {
     navigateBack()
   } else {
-    this.$emit('backClick')
+    emits('backClick')
   }
 }
 
 const toSetting = () => {
-  debounce.secondCountDown('toSetting', {
+  debounces.secondCountDown('toSetting', {
     time: 5000,
     limit: 10,
     repetition_time: 0,
@@ -73,4 +75,10 @@ const toSetting = () => {
   font-size: 35rpx;
   color: #cccccc;
 }
+
+.back-box {
+  //width: 30vw;
+  height: 200px;
+  z-index: 99;
+}
 </style>

+ 25 - 39
plugins/ly-icon.vue

@@ -1,49 +1,35 @@
 <template>
-  <i class="icon" :class="[name]" :style="[fontStyle]"></i>
+  <i :class="[name]" :style="[fontStyle]" class="icon"></i>
 </template>
 
-<script>
+<script setup>
+import {computed} from "vue";
 
-export default {
-  props: {
-    name: String,
+const emits = defineEmits(['click'])
 
-    // 字体大小
-    size: {
-      type: [Number, String],
-      default: ''
-    },
-    color: {
-      type: String,
-      default: ''
-    }
-  },
-  data() {
-    return {
-      // fontStyle:{}
-    }
-  },
-  onLoad() {
-    // if (this.size) this.fontStyle.fontSize = this.size + uni.$u.config.unit
-    // if (this.color) this.fontStyle.color = this.color
-  },
-  computed: {
-    fontStyle() {
-      const style = {}
-      if (this.size) style.fontSize = this.size + uni.$u.config.unit
-      if (this.color) style.color = this.color
-      return style
-    },
-  },
-  beforeCreate() {
-
-  },
-  methods: {
-    onClick() {
-      this.$emit('click')
-    }
+const props = defineProps({
+  name: String,
+  // 字体大小
+  size: {
+    type: [Number, String],
+    default: ''
   },
+  color: {
+    type: String,
+    default: ''
+  }
+})
+const onClick = () => {
+  emits('click')
 }
+
+const fontStyle = computed(() => {
+  const style = {}
+  if (props.size) style.fontSize = props.size + uni.$uv.config.unit
+  if (props.color) style.color = props.color
+  return style
+})
+
 </script>
 
 <style scoped>

+ 135 - 0
plugins/ly-modal.vue

@@ -0,0 +1,135 @@
+<template>
+  <view class="modal-box">
+    <uv-modal
+      ref="modelBox"
+      :align="pd.align"
+      :asyncClose="pd.asyncClose"
+      :buttonReverse="pd.buttonReverse"
+      :cancelColor="pd.cancelColor"
+      :cancelText="pd.cancelText"
+      :closeOnClickOverlay="pd.closeOnClickOverlay"
+      :confirmColor="pd.confirmColor"
+      :confirmText="pd.confirmText"
+      :content="pd.content"
+      :negativeTop="pd.negativeTop"
+      :showCancelButton="pd.showCancelButton"
+      :showConfirmButton="pd.showConfirmButton"
+      :textStyle="pd.textStyle"
+      :title="pd.title"
+      :width="pd.width"
+      :zIndex="pd.zIndex"
+      :zoom="pd.zoom"
+      @cancel="cancel"
+      @close="closeHandle"
+      @confirm="confirm">
+      <view v-if='pd.slotData && pd.slotData.open == true'>
+        <uv-input v-if="pd.slotData.type == 'input'"
+                  v-model="commitData.input"
+                  :customStyle="{height:pd.slotData.height || '40rpx',width:pd.slotData.width || '200rpx'}"
+                  :inputAlign="pd.slotData.textAlign || 'left'"
+                  :type="pd.slotData.inputType || 'text'"
+        >
+          <template v-if="pd.slotData.openend" slot="suffix">
+            <text>{{ pd.slotData.endTxt }}</text>
+          </template>
+        </uv-input>
+        <view v-if="pd.slotData.type == 'text'">{{ pd.content }}</view>
+        <slot v-if="pd.slotData.type == 'slot'"></slot>
+      </view>
+      <slot/>
+    </uv-modal>
+  </view>
+</template>
+
+<script setup>
+import {reactive, ref} from "vue";
+import {sleep} from "@/utils/util";
+
+const defaultData = {
+  title: '',
+  content: '',
+  confirmText: '确认',
+  cancelText: '取消',
+  showConfirmButton: true,
+  showCancelButton: false,
+  confirmColor: '#2979ff',
+  cancelColor: '#606266',
+  buttonReverse: false,
+  zoom: true,
+  asyncClose: false,
+  closeOnClickOverlay: true,
+  negativeTop: 0,
+  width: '650rpx',
+  zIndex: 10075,
+  align: 'left',
+  textStyle: {},
+  cancel: null,
+  close: null,
+  confirm: null,
+  /**
+   * slotData:{
+   *   open Boolean 是否打开插槽
+   *   type String 插槽属性 { input , text , slot}
+   *   type:input {
+   *      openend Boolean 打开input的后插槽
+   *      endTxt String 后插槽文字
+   *      width String input宽度
+   *      height String input高度
+   *      textAlign String 输入框文字排版 center left right
+   *    }
+   * }
+   * **/
+  slotData: {},
+}
+const show = ref(false)
+const modelBox = ref()
+let pd = reactive({...defaultData})
+
+const open = async (row) => {
+  if (show.value) {
+    close()
+    await sleep(100)
+  }
+  for (const key in pd) {
+    if (defaultData.hasOwnProperty(key)) {
+      pd[key] = defaultData[key];
+    } else {
+      delete pd[key];
+    }
+  }
+  // 应用新的row值到pd
+  for (const key in row) {
+    pd[key] = row[key];
+  }
+  modelBox.value.open()
+  show.value = true
+}
+const closeHandle = () => {
+  console.log('closeHandle')
+}
+
+const close = () => {
+  console.log('close')
+  // modelBox.value.close()
+  show.value = false
+}
+const cancel = () => {
+  console.log('cancel')
+  if (pd.cancel) pd.cancel()
+}
+const confirm = () => {
+  console.log('confirm')
+  if (pd.confirm) pd.confirm()
+}
+
+defineExpose({
+  open,
+  close,
+  cancel,
+  confirm,
+})
+</script>
+
+<style lang="less" scoped>
+
+</style>

+ 2 - 1
store/useConfigStore.js

@@ -4,7 +4,7 @@ import platform from "@/utils/platform";
 
 export const useConfigStore = defineStore('config', {
   state: () => ({
-    mType: 0, // 1 BMI;2 肺活量;3 视力;
+    mType: 0, // 7 BMI;8 肺活量;9 视力;
     mName: '',
     platform,
   }),
@@ -13,6 +13,7 @@ export const useConfigStore = defineStore('config', {
     _init() {
       // this.platform = ()
       this.getMachineType()
+      this.mType = 7
     },
     setMachineType(item) {
       storage.setKey('machineType', {

+ 56 - 43
utils/debounce.js

@@ -12,6 +12,61 @@ class Debounce {
   // interrupt: 中断事件
   // wait: 倒计时时间
 
+  // 执行防抖操作的方法
+  do(key, callback, wait = 300) {
+    if (this.timers.has(key)) {
+      clearTimeout(this.timers.get(key));
+    }
+
+    const timer = setTimeout(() => {
+      callback();
+      this.timers.delete(key);
+    }, wait);
+
+    this.timers.set(key, timer);
+  }
+
+  /**
+   *
+   * @param key
+   * @param options
+   * @param {number} [options.duration=10000] - 总倒计时时长(毫秒)。
+   * @param {function} [options.callback=null] - 每秒回调事件。
+   * @param {function} [options.endCallback=null] - 倒计时结束事件。
+   * @param {function} [options.restart=false] - 再次点击是否重新计时。
+   */
+  countDown(key, options) {
+    let op = {
+      duration: options.duration || 10000, // 总倒计时时长(毫秒)
+      callback: options.callback || null, // 每秒回调事件
+      endCallback: options.endCallback || null, // 倒计时结束事件
+      restart: options.restart || false, // 是否点击重新计时
+    };
+    if (op.restart || !this.counters.has(key)) {
+      const tick = () => {
+        const timer = this.counters.get(key);
+        if (timer.remainingTime <= 0) {
+          clearTimeout(timer.timeoutId);
+          if (op.endCallback) op.endCallback();
+          this.counters.delete(key);
+        } else {
+          timer.remainingTime -= 1000;
+          if (op.callback) op.callback(Math.ceil(timer.remainingTime / 1000));
+          timer.timeoutId = setTimeout(tick, 1000);
+          this.counters.set(key, timer);
+        }
+      };
+
+      this.counters.set(key, {
+        remainingTime: op.duration,
+        timeoutId: setTimeout(tick, 1000),
+      });
+
+      // 立即执行一次回调
+      if (op.callback) op.callback(Math.ceil(op.duration / 1000));
+    }
+  }
+
   /**
    * 开始一个倒计时,支持每秒回调、成功和失败事件。
    * @param {string} key - 倒计时的唯一标识。
@@ -24,7 +79,7 @@ class Debounce {
    * @param {boolean} [options.restart_time=false] - 是否点击重新计时。
    * @param {boolean} [options.repetition_time=0] - 重复点击限制时长(毫秒)。
    */
-  static secondCountDown(key, options = {}) {
+  secondCountDown(key, options = {}) {
     let op = {
       time: options.time || 10000, // 总倒计时长(毫秒)
       limit: options.limit || 5, // 连续操作的次数目标
@@ -99,48 +154,6 @@ class Debounce {
     }
   }
 
-  // 执行防抖操作的方法
-  do(key, callback, wait = 300) {
-    if (this.timers.has(key)) {
-      clearTimeout(this.timers.get(key));
-    }
-
-    const timer = setTimeout(() => {
-      callback();
-      this.timers.delete(key);
-    }, wait);
-
-    this.timers.set(key, timer);
-  }
-
-  // limit: 连续点击次数限制
-  countDown(key, callback, interrupt, wait = 300, limit = 3) {
-    let counter = this.counters.get(key) || {count: 0, timer: null};
-
-    // 如果达到连续点击次数限制,则清除计时器并执行目标事件
-    if (counter.count + 1 >= limit) {
-      clearTimeout(counter.timer);
-      callback();
-      this.counters.delete(key);
-      return;
-    }
-
-    // 更新计数器
-    counter.count += 1;
-    this.counters.set(key, counter);
-
-    // 设置或重置倒计时
-    if (counter.timer) {
-      clearTimeout(counter.timer);
-    }
-    counter.timer = setTimeout(() => {
-      // 倒计时结束后执行中断事件,并重置计数器
-      interrupt();
-      this.counters.delete(key);
-    }, wait);
-
-    this.counters.set(key, counter);
-  }
 
   clearDebounce(key) {
     let counter = this.counters.get(key)

+ 3 - 3
utils/machine/config.js

@@ -1,19 +1,19 @@
 export const machineTypeList = [
   {
     name: 'BMI',
-    type: 1,
+    type: 7,
     checked: false,
     disabled: false,
   },
   {
     name: '肺活量',
-    type: 2,
+    type: 8,
     checked: false,
     disabled: false,
   },
   {
     name: '视力',
-    type: 3,
+    type: 9,
     checked: false,
     disabled: false,
   },

+ 163 - 152
utils/request/upload/qiniuUploader.js

@@ -1,169 +1,180 @@
 // created by gpake
-(function () {
 
-    var config = {
-        qiniuRegion: '',
-        qiniuImageURLPrefix: '',
-        qiniuUploadToken: '',
-        qiniuUploadTokenURL: '',
-        qiniuUploadTokenFunction: null,
-        qiniuShouldUseQiniuFileName: false
-    }
 
-    module.exports = {
-        init: init,
-        upload: upload,
-    }
+let config = {
+  qiniuRegion: '',
+  qiniuImageURLPrefix: '',
+  qiniuUploadToken: '',
+  qiniuUploadTokenURL: '',
+  qiniuUploadTokenFunction: null,
+  qiniuShouldUseQiniuFileName: false
+};
 
-    // 在整个程序生命周期中,只需要 init 一次即可
-    // 如果需要变更参数,再调用 init 即可
-    function init(options) {
-        config = {
-            qiniuRegion: '',
-            qiniuImageURLPrefix: '',
-            qiniuUploadToken: '',
-            qiniuUploadTokenURL: '',
-            qiniuUploadTokenFunction: null,
-            qiniuShouldUseQiniuFileName: false
-        };
-        updateConfigWithOptions(options);
-    }
 
-    function updateConfigWithOptions(options) {
-        if (options.region) {
-            config.qiniuRegion = options.region;
-        } else {
-            console.error('qiniu uploader need your bucket region');
-        }
-        if (options.uptoken) {
-            config.qiniuUploadToken = options.uptoken;
-        } else if (options.uptokenURL) {
-            config.qiniuUploadTokenURL = options.uptokenURL;
-        } else if (options.uptokenFunc) {
-            config.qiniuUploadTokenFunction = options.uptokenFunc;
-        }
-        if (options.domain) {
-            config.qiniuImageURLPrefix = options.domain;
-        }
-        config.qiniuShouldUseQiniuFileName = options.shouldUseQiniuFileName
+// 在整个程序生命周期中,只需要 init 一次即可
+// 如果需要变更参数,再调用 init 即可
+function init(options) {
+  config = {
+    qiniuRegion: '',
+    qiniuImageURLPrefix: '',
+    qiniuUploadToken: '',
+    qiniuUploadTokenURL: '',
+    qiniuUploadTokenFunction: null,
+    qiniuShouldUseQiniuFileName: false
+  };
+  updateConfigWithOptions(options);
+}
+
+function updateConfigWithOptions(options) {
+  if (options.region) {
+    config.qiniuRegion = options.region;
+  } else {
+    console.error('qiniu uploader need your bucket region');
+  }
+  if (options.uptoken) {
+    config.qiniuUploadToken = options.uptoken;
+  } else if (options.uptokenURL) {
+    config.qiniuUploadTokenURL = options.uptokenURL;
+  } else if (options.uptokenFunc) {
+    config.qiniuUploadTokenFunction = options.uptokenFunc;
+  }
+  if (options.domain) {
+    config.qiniuImageURLPrefix = options.domain;
+  }
+  config.qiniuShouldUseQiniuFileName = options.shouldUseQiniuFileName
+}
+
+function upload(filePath, success, fail, options, progress, cancelTask) {
+  if (null == filePath) {
+    console.error('qiniu uploader need filePath to upload');
+    return;
+  }
+  if (options) {
+    updateConfigWithOptions(options);
+  }
+  if (config.qiniuUploadToken) {
+    doUpload(filePath, success, fail, options, progress, cancelTask);
+  } else if (config.qiniuUploadTokenURL) {
+    getQiniuToken(function () {
+      doUpload(filePath, success, fail, options, progress, cancelTask);
+    });
+  } else if (config.qiniuUploadTokenFunction) {
+    config.qiniuUploadToken = config.qiniuUploadTokenFunction();
+    if (null == config.qiniuUploadToken && config.qiniuUploadToken.length > 0) {
+      console.error('qiniu UploadTokenFunction result is null, please check the return value');
+      return
     }
+    doUpload(filePath, success, fail, options, progress, cancelTask);
+  } else {
+    console.error('qiniu uploader need one of [uptoken, uptokenURL, uptokenFunc]');
+    return;
+  }
+}
 
-    function upload(filePath, success, fail, options, progress, cancelTask) {
-        if (null == filePath) {
-            console.error('qiniu uploader need filePath to upload');
-            return;
+function doUpload(filePath, success, fail, options, progress, cancelTask) {
+  if (null == config.qiniuUploadToken && config.qiniuUploadToken.length > 0) {
+    console.error('qiniu UploadToken is null, please check the init config or networking');
+    return
+  }
+  const url = uploadURLFromRegionCode(config.qiniuRegion);
+  let fileName = filePath.split('//')[1];
+  if (options && options.key) {
+    fileName = options.key;
+  }
+  const formData = {
+    'token': config.qiniuUploadToken
+  };
+  if (!config.qiniuShouldUseQiniuFileName) {
+    formData['key'] = fileName
+  }
+  const uploadTask = wx.uploadFile({
+    url: url,
+    filePath: filePath,
+    name: 'file',
+    formData: formData,
+    success: function (res) {
+      var dataString = res.data
+      if (res.data.hasOwnProperty('type') && res.data.type === 'Buffer') {
+        dataString = String.fromCharCode.apply(null, res.data.data)
+      }
+      try {
+        const dataObject = JSON.parse(dataString);
+        //do something
+        const imageUrl = config.qiniuImageURLPrefix + '/' + dataObject.key;
+        dataObject.imageURL = imageUrl;
+        if (success) {
+          success(dataObject);
         }
-        if (options) {
-            updateConfigWithOptions(options);
-        }
-        if (config.qiniuUploadToken) {
-            doUpload(filePath, success, fail, options, progress, cancelTask);
-        } else if (config.qiniuUploadTokenURL) {
-            getQiniuToken(function () {
-                doUpload(filePath, success, fail, options, progress, cancelTask);
-            });
-        } else if (config.qiniuUploadTokenFunction) {
-            config.qiniuUploadToken = config.qiniuUploadTokenFunction();
-            if (null == config.qiniuUploadToken && config.qiniuUploadToken.length > 0) {
-                console.error('qiniu UploadTokenFunction result is null, please check the return value');
-                return
-            }
-            doUpload(filePath, success, fail, options, progress, cancelTask);
-        } else {
-            console.error('qiniu uploader need one of [uptoken, uptokenURL, uptokenFunc]');
-            return;
+      } catch (e) {
+        console.log('parse JSON failed, origin String is: ' + dataString)
+        if (fail) {
+          fail(e);
         }
+      }
+    },
+    fail: function (error) {
+      console.error(error);
+      if (fail) {
+        fail(error);
+      }
     }
+  });
 
-    function doUpload(filePath, success, fail, options, progress, cancelTask) {
-        if (null == config.qiniuUploadToken && config.qiniuUploadToken.length > 0) {
-            console.error('qiniu UploadToken is null, please check the init config or networking');
-            return
-        }
-        var url = uploadURLFromRegionCode(config.qiniuRegion);
-        var fileName = filePath.split('//')[1];
-        if (options && options.key) {
-            fileName = options.key;
-        }
-        var formData = {
-            'token': config.qiniuUploadToken
-        };
-        if (!config.qiniuShouldUseQiniuFileName) {
-            formData['key'] = fileName
-        }
-        var uploadTask = wx.uploadFile({
-            url: url,
-            filePath: filePath,
-            name: 'file',
-            formData: formData,
-            success: function (res) {
-                var dataString = res.data
-                if (res.data.hasOwnProperty('type') && res.data.type === 'Buffer') {
-                    dataString = String.fromCharCode.apply(null, res.data.data)
-                }
-                try {
-                    var dataObject = JSON.parse(dataString);
-                    //do something
-                    var imageUrl = config.qiniuImageURLPrefix + '/' + dataObject.key;
-                    dataObject.imageURL = imageUrl;
-                    if (success) {
-                        success(dataObject);
-                    }
-                } catch (e) {
-                    console.log('parse JSON failed, origin String is: ' + dataString)
-                    if (fail) {
-                        fail(e);
-                    }
-                }
-            },
-            fail: function (error) {
-                console.error(error);
-                if (fail) {
-                    fail(error);
-                }
-            }
-        })
+  uploadTask.onProgressUpdate((res) => {
+    progress && progress(res)
+  })
 
-        uploadTask.onProgressUpdate((res) => {
-            progress && progress(res)
-        })
+  cancelTask && cancelTask(() => {
+    uploadTask.abort()
+  })
+}
 
-        cancelTask && cancelTask(() => {
-            uploadTask.abort()
-        })
+function getQiniuToken(callback) {
+  wx.request({
+    url: config.qiniuUploadTokenURL,
+    success: function (res) {
+      const token = res.data.uptoken;
+      if (token && token.length > 0) {
+        config.qiniuUploadToken = token;
+        if (callback) {
+          callback();
+        }
+      } else {
+        console.error('qiniuUploader cannot get your token, please check the uptokenURL or server')
+      }
+    },
+    fail: function (error) {
+      console.error('qiniu UploadToken is null, please check the init config or networking: ' + error);
     }
+  })
+}
 
-    function getQiniuToken(callback) {
-        wx.request({
-            url: config.qiniuUploadTokenURL,
-            success: function (res) {
-                var token = res.data.uptoken;
-                if (token && token.length > 0) {
-                    config.qiniuUploadToken = token;
-                    if (callback) {
-                        callback();
-                    }
-                } else {
-                    console.error('qiniuUploader cannot get your token, please check the uptokenURL or server')
-                }
-            },
-            fail: function (error) {
-                console.error('qiniu UploadToken is null, please check the init config or networking: ' + error);
-            }
-        })
-    }
+function uploadURLFromRegionCode(code) {
+  let uploadURL = null;
+  switch (code) {
+    case 'ECN':
+      uploadURL = 'https://up.qbox.me';
+      break;
+    case 'NCN':
+      uploadURL = 'https://up-z1.qbox.me';
+      break;
+    case 'SCN':
+      uploadURL = 'https://up-z2.qbox.me';
+      break;
+    case 'NA':
+      uploadURL = 'https://up-na0.qbox.me';
+      break;
+    case 'ASG':
+      uploadURL = 'https://up-as0.qbox.me';
+      break;
+    default:
+      console.error('please make the region is with one of [ECN, SCN, NCN, NA, ASG]');
+  }
+  return uploadURL;
+}
 
-    function uploadURLFromRegionCode(code) {
-        var uploadURL = null;
-        switch (code) {
-            case 'ECN': uploadURL = 'https://up.qbox.me'; break;
-            case 'NCN': uploadURL = 'https://up-z1.qbox.me'; break;
-            case 'SCN': uploadURL = 'https://up-z2.qbox.me'; break;
-            case 'NA': uploadURL = 'https://up-na0.qbox.me'; break;
-            case 'ASG': uploadURL = 'https://up-as0.qbox.me'; break;
-            default: console.error('please make the region is with one of [ECN, SCN, NCN, NA, ASG]');
-        }
-        return uploadURL;
-    }
+export default {
+  init: init,
+  upload: upload,
+}
 
-})();

+ 221 - 214
utils/request/upload/upload.js

@@ -1,227 +1,234 @@
 import request from "./../core/request";
-const {
-    chooseFile,
-    chooseImage,
-    chooseVideo,
-    qiniuUpload,
-    urlUpload
-} = require("./utils");
 import {
-    mergeConfig
+  chooseFile,
+  chooseImage,
+  chooseVideo,
+  qiniuUpload,
+  urlUpload
+} from "./utils"
+import {
+  mergeConfig
 } from "./../core/utils.js";
+
 export default class fileUpload extends request {
-    constructor(props) {
-        // 调用实现父类的构造函数
-        super(props);
-    }
-    //七牛云上传任意文件
-    async qnChooseUpload(options = {}) {
-        let files;
-        try {
-            files = await chooseFile(options);
-            // 选择完成回调
-            options.onSelectComplete && options.onSelectComplete(files);
-        } catch (err) {
-            this.requestError && this.requestError(err);
-            return Promise.reject(err);
-        }
-        if (files) {
-            return this.qnFileUpload({
-                ...options,
-                files: files
-            });
-        }
+  constructor(props) {
+    // 调用实现父类的构造函数
+    super(props);
+  }
+
+  //七牛云上传任意文件
+  async qnChooseUpload(options = {}) {
+    let files;
+    try {
+      files = await chooseFile(options);
+      // 选择完成回调
+      options.onSelectComplete && options.onSelectComplete(files);
+    } catch (err) {
+      this.requestError && this.requestError(err);
+      return Promise.reject(err);
     }
-    //七牛云上传图片
-    async qnImgUpload(options = {}) {
-        let files;
-        try {
-            files = await chooseImage(options);
-            // 选择完成回调
-            options.onSelectComplete && options.onSelectComplete(files);
-        } catch (err) {
-            this.requestError && this.requestError(err);
-            return Promise.reject(err);
-        }
-        if (files) {
-            return this.qnFileUpload({
-                ...options,
-                files: files
-            });
-        }
+    if (files) {
+      return this.qnFileUpload({
+        ...options,
+        files: files
+      });
     }
-    //七牛云上传视频
-    async qnVideoUpload(options = {}) {
-        let files;
-        try {
-            files = await chooseVideo(options);
-            // 选择完成回调
-            options.onSelectComplete && options.onSelectComplete(files);
-        } catch (err) {
-            this.requestError && this.requestError(err);
-            return Promise.reject(err);
-        }
-        if (files) {
-            return this.qnFileUpload({
-                ...options,
-                files: files
-            });
-        }
+  }
+
+  //七牛云上传图片
+  async qnImgUpload(options = {}) {
+    let files;
+    try {
+      files = await chooseImage(options);
+      // 选择完成回调
+      options.onSelectComplete && options.onSelectComplete(files);
+    } catch (err) {
+      this.requestError && this.requestError(err);
+      return Promise.reject(err);
     }
+    if (files) {
+      return this.qnFileUpload({
+        ...options,
+        files: files
+      });
+    }
+  }
 
-    //七牛云文件上传(支持多张上传)
-    async qnFileUpload(options = {}) {
-        let requestInfo;
-        try {
-            // 数据合并
-            requestInfo = {
-                ...this.config,
-                ...options,
-                header: {},
-                method: "FILE"
-            };
-            //请求前回调
-            if (this.requestStart) {
-                let requestStart = this.requestStart(requestInfo);
-                if (typeof requestStart == "object") {
-                    let changekeys = ["load", "files"];
-                    changekeys.forEach(key => {
-                        requestInfo[key] = requestStart[key];
-                    });
-                } else {
-                    throw {
-                        errMsg: "【request】请求开始拦截器未通过",
-                        statusCode: 0,
-                        data: requestInfo.data,
-                        method: requestInfo.method,
-                        header: requestInfo.header,
-                        url: requestInfo.url,
-                    }
-                }
-            }
-            let requestResult = await qiniuUpload(requestInfo, this.getQnToken);
-            return Promise.resolve(requestResult);
-        } catch (err) {
-            this.requestError && this.requestError(err);
-            return Promise.reject(err);
-        } finally {
-            this.requestEnd && this.requestEnd(requestInfo);
-        }
+  //七牛云上传视频
+  async qnVideoUpload(options = {}) {
+    let files;
+    try {
+      files = await chooseVideo(options);
+      // 选择完成回调
+      options.onSelectComplete && options.onSelectComplete(files);
+    } catch (err) {
+      this.requestError && this.requestError(err);
+      return Promise.reject(err);
     }
-    //本地服务器图片上传
-    async urlImgUpload() {
-        let options = {};
-        if (arguments[0]) {
-            if (typeof(arguments[0]) == "string") {
-                options.url = arguments[0];
-            } else if (typeof(arguments[0]) == "object") {
-                options = Object.assign(options, arguments[0]);
-            }
-        }
-        if (arguments[1] && typeof(arguments[1]) == "object") {
-            options = Object.assign(options, arguments[1]);
-        }
-        try {
-            options.files = await chooseImage(options);
-            // 选择完成回调
-            options.onSelectComplete && options.onSelectComplete(options.files);
-        } catch (err) {
-            this.requestError && this.requestError(err);
-            return Promise.reject(err);
-        }
-        if (options.files) {
-            return this.urlFileUpload(options);
-        }
+    if (files) {
+      return this.qnFileUpload({
+        ...options,
+        files: files
+      });
     }
-    //本地服务器上传视频
-    async urlVideoUpload() {
-        let options = {};
-        if (arguments[0]) {
-            if (typeof(arguments[0]) == "string") {
-                options.url = arguments[0];
-            } else if (typeof(arguments[0]) == "object") {
-                options = Object.assign(options, arguments[0]);
-            }
-        }
-        if (arguments[1] && typeof(arguments[1]) == "object") {
-            options = Object.assign(options, arguments[1]);
-        }
-        try {
-            options.files = await chooseVideo(options);
-            // 选择完成回调
-            options.onSelectComplete && options.onSelectComplete(options.files);
-        } catch (err) {
-            this.requestError && this.requestError(err);
-            return Promise.reject(err);
-        }
-        if (options.files) {
-            return this.urlFileUpload(options);
-        }
+  }
+
+  //七牛云文件上传(支持多张上传)
+  async qnFileUpload(options = {}) {
+    let requestInfo;
+    try {
+      // 数据合并
+      requestInfo = {
+        ...this.config,
+        ...options,
+        header: {},
+        method: "FILE"
+      };
+      //请求前回调
+      if (this.requestStart) {
+        let requestStart = this.requestStart(requestInfo);
+        if (typeof requestStart == "object") {
+          let changekeys = ["load", "files"];
+          changekeys.forEach(key => {
+            requestInfo[key] = requestStart[key];
+          });
+        } else {
+          throw {
+            errMsg: "【request】请求开始拦截器未通过",
+            statusCode: 0,
+            data: requestInfo.data,
+            method: requestInfo.method,
+            header: requestInfo.header,
+            url: requestInfo.url,
+          }
+        }
+      }
+      let requestResult = await qiniuUpload(requestInfo, this.getQnToken);
+      return Promise.resolve(requestResult);
+    } catch (err) {
+      this.requestError && this.requestError(err);
+      return Promise.reject(err);
+    } finally {
+      this.requestEnd && this.requestEnd(requestInfo);
     }
-    //本地服务器文件上传方法
-    async urlFileUpload() {
-        let requestInfo = {
-            method: "FILE"
-        };
-        if (arguments[0]) {
-            if (typeof(arguments[0]) == "string") {
-                requestInfo.url = arguments[0];
-            } else if (typeof(arguments[0]) == "object") {
-                requestInfo = Object.assign(requestInfo, arguments[0]);
-            }
-        }
-        if (arguments[1] && typeof(arguments[1]) == "object") {
-            requestInfo = Object.assign(requestInfo, arguments[1]);
-        }
-        if (!requestInfo.url && this.defaultUploadUrl) {
-            requestInfo.url = this.defaultUploadUrl;
-        }
-        // 请求数据
-        // 是否运行过请求开始钩子
-        let runRequestStart = false;
-        try {
-            if (!requestInfo.url) {
-                throw {
-                    errMsg: "【request】文件上传缺失数据url",
-                    statusCode: 0,
-                    data: requestInfo.data,
-                    method: requestInfo.method,
-                    header: requestInfo.header,
-                    url: requestInfo.url,
-                }
-            }
-            // 数据合并
-            requestInfo = mergeConfig(this, requestInfo);
-            // 代表之前运行到这里
-            runRequestStart = true;
-            //请求前回调
-            if (this.requestStart) {
-                let requestStart = this.requestStart(requestInfo);
-                if (typeof requestStart == "object") {
-                    let changekeys = ["data", "header", "isPrompt", "load", "isFactory", "files"];
-                    changekeys.forEach(key => {
-                        requestInfo[key] = requestStart[key];
-                    });
-                } else {
-                    throw {
-                        errMsg: "【request】请求开始拦截器未通过",
-                        statusCode: 0,
-                        data: requestInfo.data,
-                        method: requestInfo.method,
-                        header: requestInfo.header,
-                        url: requestInfo.url,
-                    }
-                }
-            }
-            let requestResult = await urlUpload(requestInfo, this.dataFactory);
-            return Promise.resolve(requestResult);
-        } catch (err) {
-            this.requestError && this.requestError(err);
-            return Promise.reject(err);
-        } finally {
-            if (runRequestStart) {
-                this.requestEnd && this.requestEnd(requestInfo);
-            }
-        }
+  }
+
+  //本地服务器图片上传
+  async urlImgUpload() {
+    let options = {};
+    if (arguments[0]) {
+      if (typeof (arguments[0]) == "string") {
+        options.url = arguments[0];
+      } else if (typeof (arguments[0]) == "object") {
+        options = Object.assign(options, arguments[0]);
+      }
+    }
+    if (arguments[1] && typeof (arguments[1]) == "object") {
+      options = Object.assign(options, arguments[1]);
+    }
+    try {
+      options.files = await chooseImage(options);
+      // 选择完成回调
+      options.onSelectComplete && options.onSelectComplete(options.files);
+    } catch (err) {
+      this.requestError && this.requestError(err);
+      return Promise.reject(err);
+    }
+    if (options.files) {
+      return this.urlFileUpload(options);
+    }
+  }
+
+  //本地服务器上传视频
+  async urlVideoUpload() {
+    let options = {};
+    if (arguments[0]) {
+      if (typeof (arguments[0]) == "string") {
+        options.url = arguments[0];
+      } else if (typeof (arguments[0]) == "object") {
+        options = Object.assign(options, arguments[0]);
+      }
+    }
+    if (arguments[1] && typeof (arguments[1]) == "object") {
+      options = Object.assign(options, arguments[1]);
+    }
+    try {
+      options.files = await chooseVideo(options);
+      // 选择完成回调
+      options.onSelectComplete && options.onSelectComplete(options.files);
+    } catch (err) {
+      this.requestError && this.requestError(err);
+      return Promise.reject(err);
+    }
+    if (options.files) {
+      return this.urlFileUpload(options);
+    }
+  }
+
+  //本地服务器文件上传方法
+  async urlFileUpload() {
+    let requestInfo = {
+      method: "FILE"
+    };
+    if (arguments[0]) {
+      if (typeof (arguments[0]) == "string") {
+        requestInfo.url = arguments[0];
+      } else if (typeof (arguments[0]) == "object") {
+        requestInfo = Object.assign(requestInfo, arguments[0]);
+      }
+    }
+    if (arguments[1] && typeof (arguments[1]) == "object") {
+      requestInfo = Object.assign(requestInfo, arguments[1]);
+    }
+    if (!requestInfo.url && this.defaultUploadUrl) {
+      requestInfo.url = this.defaultUploadUrl;
+    }
+    // 请求数据
+    // 是否运行过请求开始钩子
+    let runRequestStart = false;
+    try {
+      if (!requestInfo.url) {
+        throw {
+          errMsg: "【request】文件上传缺失数据url",
+          statusCode: 0,
+          data: requestInfo.data,
+          method: requestInfo.method,
+          header: requestInfo.header,
+          url: requestInfo.url,
+        }
+      }
+      // 数据合并
+      requestInfo = mergeConfig(this, requestInfo);
+      // 代表之前运行到这里
+      runRequestStart = true;
+      //请求前回调
+      if (this.requestStart) {
+        let requestStart = this.requestStart(requestInfo);
+        if (typeof requestStart == "object") {
+          let changekeys = ["data", "header", "isPrompt", "load", "isFactory", "files"];
+          changekeys.forEach(key => {
+            requestInfo[key] = requestStart[key];
+          });
+        } else {
+          throw {
+            errMsg: "【request】请求开始拦截器未通过",
+            statusCode: 0,
+            data: requestInfo.data,
+            method: requestInfo.method,
+            header: requestInfo.header,
+            url: requestInfo.url,
+          }
+        }
+      }
+      let requestResult = await urlUpload(requestInfo, this.dataFactory);
+      return Promise.resolve(requestResult);
+    } catch (err) {
+      this.requestError && this.requestError(err);
+      return Promise.reject(err);
+    } finally {
+      if (runRequestStart) {
+        this.requestEnd && this.requestEnd(requestInfo);
+      }
     }
+  }
 }

+ 312 - 310
utils/request/upload/utils.js

@@ -1,338 +1,340 @@
-const qiniuUploader = require("./qiniuUploader");
+import qiniuUploader from "./qiniuUploader"
 //七牛云上传文件命名
-export const randomChar = function(l, url = "") {
-    const x = "0123456789qwertyuioplkjhgfdsazxcvbnm";
-    let tmp = "";
-    let time = new Date();
-    for (let i = 0; i < l; i++) {
-        tmp += x.charAt(Math.ceil(Math.random() * 100000000) % x.length);
-    }
-    return (
-        "file/" +
-        url +
-        time.getTime() +
-        tmp
-    );
+export const randomChar = function (l, url = "") {
+  const x = "0123456789qwertyuioplkjhgfdsazxcvbnm";
+  let tmp = "";
+  let time = new Date();
+  for (let i = 0; i < l; i++) {
+    tmp += x.charAt(Math.ceil(Math.random() * 100000000) % x.length);
+  }
+  return (
+    "file/" +
+    url +
+    time.getTime() +
+    tmp
+  );
 }
 //图片选择
-export const chooseImage = function(data) {
-    return new Promise((resolve, reject) => {
-        uni.chooseImage({
-            count: data.count || 9, //默认9
-            sizeType: data.sizeType || ['original', 'compressed'], //可以指定是原图还是压缩图,默认二者都有
-            sourceType: data.sourceType || ['album', 'camera'], //从相册选择
-            success: function(res) {
-                resolve(res.tempFiles);
-            },
-            fail: err => {
-                reject({
-                    errMsg: err.errMsg,
-                    errCode: err.errCode,
-                    statusCode: 0,
-                });
-            }
+export const chooseImage = function (data) {
+  return new Promise((resolve, reject) => {
+    uni.chooseImage({
+      count: data.count || 9, //默认9
+      sizeType: data.sizeType || ['original', 'compressed'], //可以指定是原图还是压缩图,默认二者都有
+      sourceType: data.sourceType || ['album', 'camera'], //从相册选择
+      success: function (res) {
+        resolve(res.tempFiles);
+      },
+      fail: err => {
+        reject({
+          errMsg: err.errMsg,
+          errCode: err.errCode,
+          statusCode: 0,
         });
+      }
     });
+  });
 }
 //视频选择
-export const chooseVideo = function(data) {
-    return new Promise((resolve, reject) => {
-        uni.chooseVideo({
-            sourceType: data.sourceType || ['album', 'camera'], //从相册选择
-            compressed: data.compressed || false, //是否压缩所选的视频源文件,默认值为 true,需要压缩。
-            maxDuration: data.maxDuration || 60, //拍摄视频最长拍摄时间,单位秒。最长支持 60 秒。
-            camera: data.camera || 'back', //'front'、'back',默认'back'
-            success: function(res) {
-                let files = [{
-                    path: res.tempFilePath
-                }];
-                // #ifdef APP-PLUS || H5 || MP-WEIXIN
-                files[0].duration = res.duration;
-                files[0].size = res.size;
-                files[0].height = res.height;
-                files[0].width = res.width;
-                // #endif
-                // #ifdef H5
-                files[0].name = res.name;
-                // #endif
-                resolve(files);
-            },
-            fail: err => {
-                reject({
-                    errMsg: err.errMsg,
-                    errCode: err.errCode,
-                    statusCode: 0,
-                });
-            }
+export const chooseVideo = function (data) {
+  return new Promise((resolve, reject) => {
+    uni.chooseVideo({
+      sourceType: data.sourceType || ['album', 'camera'], //从相册选择
+      compressed: data.compressed || false, //是否压缩所选的视频源文件,默认值为 true,需要压缩。
+      maxDuration: data.maxDuration || 60, //拍摄视频最长拍摄时间,单位秒。最长支持 60 秒。
+      camera: data.camera || 'back', //'front'、'back',默认'back'
+      success: function (res) {
+        let files = [{
+          path: res.tempFilePath
+        }];
+        // #ifdef APP-PLUS || H5 || MP-WEIXIN
+        files[0].duration = res.duration;
+        files[0].size = res.size;
+        files[0].height = res.height;
+        files[0].width = res.width;
+        // #endif
+        // #ifdef H5
+        files[0].name = res.name;
+        // #endif
+        resolve(files);
+      },
+      fail: err => {
+        reject({
+          errMsg: err.errMsg,
+          errCode: err.errCode,
+          statusCode: 0,
         });
+      }
     });
+  });
 }
 // 选择文件
-export const chooseFile = function(data) {
-    return new Promise((resolve, reject) => {
+export const chooseFile = function (data) {
+  return new Promise((resolve, reject) => {
 
-        // #ifdef MP-WEIXIN
-        uni.chooseMessageFile({
-            count:data.count ?data.count: 1,
-            type:'file',
-            extension:data.extension ? data.extension : ['jpg','jpeg','png','mp4','avi'],
-            success: function(res) {
-                let files = [
-                    // {
-                    //     path,
-                    //     size,
-                    //     name,
-                    //     type,
-                    //     time,
-                    // }
-                ];
-                res.tempFiles.forEach((item,index) => {
-                    files.push(
-                        {
-                            path:item.path,
-                            size:item.size,
-                            name:item.name,
-                            type:item.type,
-                            time:item.time,
-                        }
-                    )
-                })
-                resolve(files);
-            },
-            fail: err => {
-                reject({
-                    errMsg: err.errMsg,
-                    errCode: err.errCode,
-                    statusCode: 0,
-                });
+    // #ifdef MP-WEIXIN
+    uni.chooseMessageFile({
+      count: data.count ? data.count : 1,
+      type: 'file',
+      extension: data.extension ? data.extension : ['jpg', 'jpeg', 'png', 'mp4', 'avi'],
+      success: function (res) {
+        let files = [
+          // {
+          //     path,
+          //     size,
+          //     name,
+          //     type,
+          //     time,
+          // }
+        ];
+        res.tempFiles.forEach((item, index) => {
+          files.push(
+            {
+              path: item.path,
+              size: item.size,
+              name: item.name,
+              type: item.type,
+              time: item.time,
             }
+          )
         })
-        // #endif
-        // #ifndef MP-WEIXIN
-        // #endif
+        resolve(files);
+      },
+      fail: err => {
+        reject({
+          errMsg: err.errMsg,
+          errCode: err.errCode,
+          statusCode: 0,
+        });
+      }
+    })
+    // #endif
+    // #ifndef MP-WEIXIN
+    // #endif
 
 
-    });
+  });
 }
 // 七牛云上传
-export const qiniuUpload = function(requestInfo, getQnToken) {
-    return new Promise((resolve, reject) => {
-        if (Array.isArray(requestInfo.files)) {
-            let len = requestInfo.files.length;
-            let fileList = new Array;
-            if (getQnToken) {
-                getQnToken(qnRes => {
-                    /*
-                     *接口返回参数:
-                     *visitPrefix:访问文件的域名
-                     *token:七牛云上传token
-                     *folderPath:上传的文件夹
-                     *region: 地区 默认为:SCN
-                     */
-                    let prefixLen = qnRes.visitPrefix.length;
-                    if(qnRes.visitPrefix.charAt(prefixLen - 1) == '/'){
-                        qnRes.visitPrefix = qnRes.visitPrefix.substring(0, prefixLen - 1)
-                    }
-                    uploadFile(0);
+export const qiniuUpload = function (requestInfo, getQnToken) {
+  return new Promise((resolve, reject) => {
+    if (Array.isArray(requestInfo.files)) {
+      let len = requestInfo.files.length;
+      let fileList = new Array;
+      if (getQnToken) {
+        getQnToken(qnRes => {
+          /*
+           *接口返回参数:
+           *visitPrefix:访问文件的域名
+           *token:七牛云上传token
+           *folderPath:上传的文件夹
+           *region: 地区 默认为:SCN
+           */
+          let prefixLen = qnRes.visitPrefix.length;
+          if (qnRes.visitPrefix.charAt(prefixLen - 1) == '/') {
+            qnRes.visitPrefix = qnRes.visitPrefix.substring(0, prefixLen - 1)
+          }
+          uploadFile(0);
 
-                    function uploadFile(i) {
-                        let item = requestInfo.files[i];
-                        let updateUrl = randomChar(10, qnRes.folderPath);
-                        let fileData = {
-                            fileIndex: i,
-                            files: requestInfo.files,
-                            ...item
-                        };
-                        if (item.name) {
-                            fileData.name = item.name;
-                            let nameArr = item.name.split(".");
-                            updateUrl += "." + nameArr[nameArr.length - 1];
-                        }
-                        // 交给七牛上传
-                        qiniuUploader.upload(item.path || item, (res) => {
-                            fileData.url = res.imageURL;
-                            requestInfo.onEachUpdate && requestInfo.onEachUpdate({
-                                url: res.imageURL,
-                                ...fileData
-                            });
-                            fileList.push({
-                                name:item.name,
-                                url:res.imageURL,
-                            });
-                            if (len - 1 > i) {
-                                uploadFile(i + 1);
-                            } else {
-                                resolve(fileList);
-                            }
-                        }, (error) => {
-                            reject(error);
-                        }, {
-                            region: qnRes.region || 'SCN', //地区
-                            domain: qnRes.visitPrefix, // bucket 域名,下载资源时用到。
-                            key: updateUrl,
-                            uptoken: qnRes.token, // 由其他程序生成七牛 uptoken
-                            uptokenURL: 'UpTokenURL.com/uptoken' // 上传地址
-                        }, (res) => {
-                            console.log(requestInfo);
-                            requestInfo.onProgressUpdate && requestInfo.onProgressUpdate(Object.assign({}, fileData, res));
-                            // console.log('上传进度', res.progress)
-                            // console.log('已经上传的数据长度', res.totalBytesSent)
-                            // console.log('预期需要上传的数据总长度', res.totalBytesExpectedToSend)
-                        });
-                    }
-                });
-            } else {
-                reject({
-                    errMsg: "请添加七牛云回调方法:getQnToken",
-                    statusCode: 0
-                });
+          function uploadFile(i) {
+            let item = requestInfo.files[i];
+            let updateUrl = randomChar(10, qnRes.folderPath);
+            let fileData = {
+              fileIndex: i,
+              files: requestInfo.files,
+              ...item
+            };
+            if (item.name) {
+              fileData.name = item.name;
+              let nameArr = item.name.split(".");
+              updateUrl += "." + nameArr[nameArr.length - 1];
             }
-        } else {
-            reject({
-                errMsg: "files 必须是数组类型",
-                statusCode: 0
+            // 交给七牛上传
+            qiniuUploader.upload(item.path || item, (res) => {
+              fileData.url = res.imageURL;
+              requestInfo.onEachUpdate && requestInfo.onEachUpdate({
+                url: res.imageURL,
+                ...fileData
+              });
+              fileList.push({
+                name: item.name,
+                url: res.imageURL,
+              });
+              if (len - 1 > i) {
+                uploadFile(i + 1);
+              } else {
+                resolve(fileList);
+              }
+            }, (error) => {
+              reject(error);
+            }, {
+              region: qnRes.region || 'SCN', //地区
+              domain: qnRes.visitPrefix, // bucket 域名,下载资源时用到。
+              key: updateUrl,
+              uptoken: qnRes.token, // 由其他程序生成七牛 uptoken
+              uptokenURL: 'UpTokenURL.com/uptoken' // 上传地址
+            }, (res) => {
+              console.log(requestInfo);
+              requestInfo.onProgressUpdate && requestInfo.onProgressUpdate(Object.assign({}, fileData, res));
+              // console.log('上传进度', res.progress)
+              // console.log('已经上传的数据长度', res.totalBytesSent)
+              // console.log('预期需要上传的数据总长度', res.totalBytesExpectedToSend)
             });
-        };
-    });
+          }
+        });
+      } else {
+        reject({
+          errMsg: "请添加七牛云回调方法:getQnToken",
+          statusCode: 0
+        });
+      }
+    } else {
+      reject({
+        errMsg: "files 必须是数组类型",
+        statusCode: 0
+      });
+    }
+    ;
+  });
 }
 // 服务器URL上传
-export const urlUpload = function(requestInfo, dataFactory) {
-    return new Promise((resolve, reject) => {
-        // 本地文件上传去掉默认Content-Type
-        if (requestInfo.header['Content-Type']) {
-            delete requestInfo.header['Content-Type'];
-        }
-        // 本地文件上传去掉默认Content-Type
-        if (requestInfo.header['content-type']) {
-            delete requestInfo.header['content-type'];
-        }
-        if (Array.isArray(requestInfo.files)) {
-            // // #ifdef APP-PLUS || H5
-            // let files = [];
-            // let fileData = {
-            // 	files: requestInfo.files,
-            // 	name: requestInfo.name || "file"
-            // };
-            // requestInfo.files.forEach(item => {
-            //              let fileInfo = {
-            //                  name: requestInfo.name || "file",
-            //              };
-            //              if(item.path){
-            //                  fileInfo.uri = item.path;
-            //              } else {
-            //                  fileInfo.file = item;
-            //              }
-            // 	files.push(fileInfo);
-            // });
-            // let config = {
-            // 	url: requestInfo.url,
-            // 	files: files,
-            // 	header: requestInfo.header, //加入请求头
-            // 	success: (response) => {
-            // 		//是否用外部的数据处理方法
-            // 		if (requestInfo.isFactory && dataFactory) {
-            // 			//数据处理
-            // 			dataFactory({
-            // 				...requestInfo,
-            // 				response: response,
-            // 			}).then(data => {
-            // 				requestInfo.onEachUpdate && requestInfo.onEachUpdate({
-            // 					data: data,
-            // 					...fileData
-            // 				});
-            // 				resolve(data);
-            // 			},err => {
-            // 				reject(err);
-            // 			});
-            // 		} else {
-            // 			requestInfo.onEachUpdate && requestInfo.onEachUpdate({
-            // 				data: response,
-            // 				...fileData
-            // 			});
-            // 			resolve(response);
-            // 		}
-            // 	},
-            // 	fail: (err) => {
-            // 		reject(err);
-            // 	}
-            // };
-            // if (requestInfo.data) {
-            // 	config.formData = requestInfo.data;
-            // }
-            // const uploadTask = uni.uploadFile(config);
-            // uploadTask.onProgressUpdate(res => {
-            // 	requestInfo.onProgressUpdate && requestInfo.onProgressUpdate(Object.assign({}, fileData, res));
-            // });
-            // // #endif
-            // #-ifdef MP
-            const len = requestInfo.files.length - 1;
-            let fileList = new Array;
-            fileUpload(0);
+export const urlUpload = function (requestInfo, dataFactory) {
+  return new Promise((resolve, reject) => {
+    // 本地文件上传去掉默认Content-Type
+    if (requestInfo.header['Content-Type']) {
+      delete requestInfo.header['Content-Type'];
+    }
+    // 本地文件上传去掉默认Content-Type
+    if (requestInfo.header['content-type']) {
+      delete requestInfo.header['content-type'];
+    }
+    if (Array.isArray(requestInfo.files)) {
+      // // #ifdef APP-PLUS || H5
+      // let files = [];
+      // let fileData = {
+      // 	files: requestInfo.files,
+      // 	name: requestInfo.name || "file"
+      // };
+      // requestInfo.files.forEach(item => {
+      //              let fileInfo = {
+      //                  name: requestInfo.name || "file",
+      //              };
+      //              if(item.path){
+      //                  fileInfo.uri = item.path;
+      //              } else {
+      //                  fileInfo.file = item;
+      //              }
+      // 	files.push(fileInfo);
+      // });
+      // let config = {
+      // 	url: requestInfo.url,
+      // 	files: files,
+      // 	header: requestInfo.header, //加入请求头
+      // 	success: (response) => {
+      // 		//是否用外部的数据处理方法
+      // 		if (requestInfo.isFactory && dataFactory) {
+      // 			//数据处理
+      // 			dataFactory({
+      // 				...requestInfo,
+      // 				response: response,
+      // 			}).then(data => {
+      // 				requestInfo.onEachUpdate && requestInfo.onEachUpdate({
+      // 					data: data,
+      // 					...fileData
+      // 				});
+      // 				resolve(data);
+      // 			},err => {
+      // 				reject(err);
+      // 			});
+      // 		} else {
+      // 			requestInfo.onEachUpdate && requestInfo.onEachUpdate({
+      // 				data: response,
+      // 				...fileData
+      // 			});
+      // 			resolve(response);
+      // 		}
+      // 	},
+      // 	fail: (err) => {
+      // 		reject(err);
+      // 	}
+      // };
+      // if (requestInfo.data) {
+      // 	config.formData = requestInfo.data;
+      // }
+      // const uploadTask = uni.uploadFile(config);
+      // uploadTask.onProgressUpdate(res => {
+      // 	requestInfo.onProgressUpdate && requestInfo.onProgressUpdate(Object.assign({}, fileData, res));
+      // });
+      // // #endif
+      // #-ifdef MP
+      const len = requestInfo.files.length - 1;
+      let fileList = new Array;
+      fileUpload(0);
 
-            function fileUpload(i) {
-                let item = requestInfo.files[i];
-                let fileData = {
-                    fileIndex: i,
-                    files: requestInfo.files,
-                    ...item
-                };
-                let config = {
-                    url: requestInfo.url,
-                    filePath: item.path,
-                    header: requestInfo.header, //加入请求头
-                    name: requestInfo.name || "file",
-                    success: (response) => {
-                        //是否用外部的数据处理方法
-                        if (requestInfo.isFactory && dataFactory) {
-                            //数据处理
-                            dataFactory({
-                                ...requestInfo,
-                                response: response,
-                            }).then(data => {
-                                fileList.push(data);
-                                requestInfo.onEachUpdate && requestInfo.onEachUpdate({
-                                    data: data,
-                                    ...fileData
-                                });
-                                if (len <= i) {
-                                    resolve(fileList);
-                                } else {
-                                    fileUpload(i + 1);
-                                }
-                            },err => {
-                                reject(err);
-                            });
-                        } else {
-                            requestInfo.onEachUpdate && requestInfo.onEachUpdate({
-                                data: response,
-                                ...fileData
-                            });
-                            fileList.push(response);
-                            if (len <= i) {
-                                resolve(fileList);
-                            } else {
-                                fileUpload(i + 1);
-                            }
-                        }
-                    },
-                    fail: (err) => {
-                        reject(err);
-                    }
-                };
-                if (requestInfo.data) {
-                    config.formData = requestInfo.data;
-                }
-                const uploadTask = uni.uploadFile(config);
-                uploadTask.onProgressUpdate(res => {
-                    requestInfo.onProgressUpdate && requestInfo.onProgressUpdate(Object.assign({}, fileData, res));
+      function fileUpload(i) {
+        let item = requestInfo.files[i];
+        let fileData = {
+          fileIndex: i,
+          files: requestInfo.files,
+          ...item
+        };
+        let config = {
+          url: requestInfo.url,
+          filePath: item.path,
+          header: requestInfo.header, //加入请求头
+          name: requestInfo.name || "file",
+          success: (response) => {
+            //是否用外部的数据处理方法
+            if (requestInfo.isFactory && dataFactory) {
+              //数据处理
+              dataFactory({
+                ...requestInfo,
+                response: response,
+              }).then(data => {
+                fileList.push(data);
+                requestInfo.onEachUpdate && requestInfo.onEachUpdate({
+                  data: data,
+                  ...fileData
                 });
+                if (len <= i) {
+                  resolve(fileList);
+                } else {
+                  fileUpload(i + 1);
+                }
+              }, err => {
+                reject(err);
+              });
+            } else {
+              requestInfo.onEachUpdate && requestInfo.onEachUpdate({
+                data: response,
+                ...fileData
+              });
+              fileList.push(response);
+              if (len <= i) {
+                resolve(fileList);
+              } else {
+                fileUpload(i + 1);
+              }
             }
-            // #-endif
-        } else {
-            reject({
-                errMsg: "files 必须是数组类型",
-                statusCode: 0
-            });
+          },
+          fail: (err) => {
+            reject(err);
+          }
+        };
+        if (requestInfo.data) {
+          config.formData = requestInfo.data;
         }
-    });
+        const uploadTask = uni.uploadFile(config);
+        uploadTask.onProgressUpdate(res => {
+          requestInfo.onProgressUpdate && requestInfo.onProgressUpdate(Object.assign({}, fileData, res));
+        });
+      }
+
+      // #-endif
+    } else {
+      reject({
+        errMsg: "files 必须是数组类型",
+        statusCode: 0
+      });
+    }
+  });
 }

+ 25 - 13
vite.config.js

@@ -1,11 +1,24 @@
 // Vite中文网:https://vitejs.cn/config/
-import {loadEnv} from 'vite';
 import {resolve} from 'path';
 import uni from '@dcloudio/vite-plugin-uni';
 
+const envs = require('./config/env');
+
 export default ({mode}) => {
-  const root = process.cwd();
-  const env = loadEnv(mode, root);
+  const context = JSON.parse(process.env.UNI_CUSTOM_CONTEXT)
+
+  // 默认测试服
+  let config = envs.test
+  if (!context.IS_TEST) {
+    config = envs.prod
+  }
+
+  // 默认正式服
+  // let config = envs.prod
+  // if (!context.IS_TEST) {
+  //   config = envs.test
+  // }
+
   return {
     base: './',
     // 设置路径别名
@@ -16,16 +29,16 @@ export default ({mode}) => {
       extensions: ['.js', '.json', '.ts', '.vue'], // 使用路径别名时想要省略的后缀名,可以自己 增减
     },
     // 自定义全局变量
-    // define: {
-    //   'process.env': {},
-    // },
+    define: {
+      'process.env': config,
+    },
     // 开发服务器配置
-    // server: {
-    //   host: true,
-    //   // open: true,
-    //   port: env.VITE_PORT,
-    //   proxy: {},
-    // },
+    server: {
+      host: true,
+      // open: true,
+      // port: env.VITE_PORT,
+      proxy: {},
+    },
     // 构建配置
     // build: {
     //   outDir: 'dist',
@@ -46,7 +59,6 @@ export default ({mode}) => {
     // 插件
     plugins: [
       uni(),
-      // Unocss(),
     ],
   };
 };

+ 0 - 55
vue.config.js

@@ -1,55 +0,0 @@
-// const path = require('path')
-//
-// const root = process.env.UNI_INPUT_DIR;
-// const replaceFunction = require('./build/vue.config.replace');
-// const replaceLessFunction = require('./build/vue.config.replaceLess');
-// const env = require('./env');
-//
-// // 默认测试服
-// let config = env.test
-// let commonLessFileName = 'common-dev'
-// if (process.UNI_SCRIPT_ENV && !process.UNI_SCRIPT_ENV.IS_TEST) {
-//   commonLessFileName = 'common-prod'
-//   config = env.prod
-// }
-//
-// // 默认正式服
-// // let config = env.prod
-// // let commonLessFileName = 'common-prod'
-// // if (process.UNI_SCRIPT_ENV && process.UNI_SCRIPT_ENV.IS_TEST) {
-// //     commonLessFileName = 'common-dev'
-// //     config = env.test
-// // }
-//
-// process.UNI_SCRIPT_ENV = {}
-//
-// // 向 env  写入配置参数
-// Object.keys(config).forEach(key => {
-//   process.UNI_SCRIPT_ENV[key] = config[key]
-// })
-//
-// // 读取 manifest.json ,修改后重新写入
-// replaceFunction.setData(root + "/manifestTemp.json", {
-//   'name': `"${process.UNI_SCRIPT_ENV.TITLE}"`,
-//   'mp-weixin.appid': `"${process.UNI_SCRIPT_ENV.APPID}"`,
-//   'h5.devServer.proxy./static.target': `"${process.UNI_SCRIPT_ENV.APIURL}"`,
-// }, root + "/manifest.json")
-//
-// // 更新对应配置文件的参数设置
-// replaceLessFunction.setData(root + `/${commonLessFileName}.less`, {
-//   '@bg': `"${process.UNI_SCRIPT_ENV.FILEURL}"`,
-// })
-//
-// let stylePath = path.resolve(__dirname, `./${commonLessFileName}.less`)
-// module.exports = {
-//
-//   css: {
-//     loaderOptions: {
-//       less: {
-//         globalVars: {
-//           "hack": `true; @import "${stylePath}"`
-//         }
-//       }
-//     }
-//   }
-// }