diff --git a/src/core/upload.js b/src/core/upload.js new file mode 100644 index 0000000..83d2c31 --- /dev/null +++ b/src/core/upload.js @@ -0,0 +1,48 @@ +import Vue from "vue" +let prototype = Vue.prototype; + +function findApi(name) { + let pos = name.indexOf('.'); + if (pos > 0) { + let temp, arr = name.split('.'); + for (let i = 0; i < arr.length; i++) { + if (i == 0) { + temp = prototype.$apis[arr[i]] || {}; + } else { + temp = temp[arr[i]] || {}; + } + } + return temp; + } + + return name; +} + +let upload = async (args) => { + const rule = findApi(args.api || ''); + if (JSON.stringify(rule) === "{}") { + throw "找不到API:" + args.api; + } + + (rule.showLoading) && uni.showLoading({ + title: "上传中" + }); + + let [error, response] = await uni.uploadFile({ + url: prototype.$config.root + rule.url, + filePath: args.path, + name: args.name || 'file', + formData: args.data || {}, + }); + + (rule.showLoading) && uni.hideLoading(); + + if (error) { + prototype.$utils.toast('网络错误'); + throw "网络错误"; + } + + return Promise.resolve(JSON.parse(response.data)); +} + +export default upload diff --git a/src/main.js b/src/main.js index b747772..5d077f8 100644 --- a/src/main.js +++ b/src/main.js @@ -4,6 +4,7 @@ import App from './App' import store from "./store/index" import storage from './core/storage' import request from './core/request' +import upload from './core/upload' import test from './core/libs/test' import event from './core/libs/event' import utils from './core/libs/utils' @@ -16,6 +17,7 @@ Vue.use({ install(Vue, options) { Vue.prototype.$storage = storage Vue.prototype.$request = request + Vue.prototype.$upload = upload Vue.prototype.$test = test Vue.prototype.$event = event Vue.prototype.$utils = utils