This commit is contained in:
砂糖
2026-02-07 18:01:13 +08:00
commit 8015759c65
2110 changed files with 269866 additions and 0 deletions

362
fuintUniapp/utils/app.js Normal file
View File

@@ -0,0 +1,362 @@
import store from '../store'
import * as util from './util'
import { paginate } from '@/common/constant'
import * as MessageApi from '@/api/message'
/**
* 获取当前运行的终端(App H5 小程序)
* https://uniapp.dcloud.io/platform
*/
export const getPlatform = () => {
// #ifdef APP-PLUS
const platform = 'App'
// #endif
// #ifdef APP-PLUS-NVUE
const platform = 'App'
// #endif
// #ifdef H5
const platform = 'H5'
// #endif
// #ifdef MP-WEIXIN
const platform = 'MP-WEIXIN'
// #endif
// #ifdef MP-ALIPAY
const platform = 'MP-ALIPAY'
// #endif
// #ifdef MP-BAIDU
const platform = 'MP-BAIDU'
// #endif
// #ifdef MP-TOUTIAO
const platform = 'MP-TOUTIAO'
// #endif
// #ifdef MP-QQ
const platform = 'MP-QQ'
// #endif
// #ifdef MP-360
const platform = 'MP-360'
// #endif
return platform;
}
/**
* 显示成功提示框
*/
export const showSuccess = (msg, callback) => {
uni.showToast({
title: msg,
icon: 'success',
mask: true,
duration: 1500,
success() {
callback && callback()
}
})
}
/**
* 显示失败提示框
*/
export const showError = (msg, callback) => {
uni.showModal({
title: '友情提示',
content: msg,
showCancel: false,
success(res) {
callback && callback()
}
})
}
/**
* 显示纯文字提示框
*/
export const showToast = msg => {
uni.showToast({
title: msg,
icon: 'none'
})
}
/**
* tabBar页面路径列表 (用于链接跳转时判断)
* tabBarLinks为常量, 无需修改
*/
export const getTabBarLinks = () => {
const tabBarLinks = [
'pages/index/index',
'pages/category/index',
'pages/user/index'
]
return tabBarLinks
}
/**
* 生成转发的url参数
*/
export const getShareUrlParams = (params) => {
let path = util.urlEncode({
spm: store.getters.userId, // 推荐人ID
...params
})
console.log('转发url : ', path);
return path;
}
/**
* 跳转到指定页面url
* 支持tabBar页面
* @param {string} url
* @param {object} query
*/
export const navTo = (url, query = {}) => {
if (!url || url.length == 0) {
return false
}
// tabBar页面, 使用switchTab
if (util.inArray(url, getTabBarLinks())) {
uni.switchTab({
url: `/${url}`
})
return true
}
// 生成query参数
const queryStr = !util.isEmpty(query) ? '?' + util.urlEncode(query) : ''
// 普通页面, 使用navigateTo
uni.navigateTo({
url: `/${url}${queryStr}`
})
return true
}
/**
* 记录购物车商品总数量
* @param {*} value
*/
export const setCartTotalNum = (value) => {
uni.setStorageSync('cartTotalNum', Number(value))
}
/**
* 设置购物车tabbar的角标
* 该方法只能在tabbar页面中调用, 其他页面调用会报错
*/
export const setCartTabBadge = () => {
const cartTabbarIndex = 1
const cartTotal = uni.getStorageSync('cartTotalNum') || 0;
console.log('cartTotal = ', cartTotal);
if (cartTotal > 0) {
uni.setTabBarBadge({
index: cartTabbarIndex,
text: `${cartTotal}`
})
} else {
uni.removeTabBarBadge({
index: cartTabbarIndex
})
}
return
}
/**
* 验证是否已登录
*/
export const checkLogin = () => {
return !!store.getters.userId;
}
/**
* 需要登录后操作
*/
export const needLogin = () => {
const isLogin = checkLogin();
if (!isLogin) {
uni.showModal({
title: '温馨提示',
content: '此时此刻需要您登录喔~',
confirmText: "去登录",
cancelText: "再逛会",
success: res => {
if (res.confirm) {
uni.navigateTo({
url: "/pages/login/index"
})
}
}
})
}
}
/**
* 发起支付请求
* @param {Object} 参数
*/
export const wxPayment = (option) => {
const options = {
timeStamp: '',
nonceStr: '',
prepay_id: '',
paySign: '',
...option
}
// 微信内浏览器支付
if (isWechat()) {
return new Promise((resolve, reject) => {
wxH5Payment(options,
function(res) {
resolve(res);
},
function(err) {
reject(err);
});
})
}
// H5支付
if (getPlatform() == 'H5' && option.mweb_url) {
h5Pay(option.mweb_url, option.backUrl);
return true;
}
// 微信小程序支付
return new Promise((resolve, reject) => {
uni.requestPayment({
provider: 'wxpay',
timeStamp: options.timeStamp,
nonceStr: options.nonceStr,
'package': options.package,
signType: 'MD5',
paySign: options.paySign,
success: res => resolve(res),
fail: res => reject(res)
})
})
}
/**
* 加载更多列表数据
* @param {Object} resList 新列表数据
* @param {Object} oldList 旧列表数据
* @param {int} pageNo 当前页码
*/
export const getEmptyPaginateObj = () => {
return util.cloneObj(paginate)
}
/**
* 加载更多列表数据
* @param {Object} resList 新列表数据
* @param {Object} oldList 旧列表数据
* @param {int} pageNo 当前页码
*/
export const getMoreListData = (resList, oldList, pageNo) => {
// 如果是第一页需手动制空列表
if (pageNo == 1) oldList.content = [];
// 合并新数据
return oldList.content.concat(resList.content);
}
/**
* 弹框消息
* @param {Object} 参数
*/
export const showMessage = () => {
const app = this
if (!store.getters.userId) {
return false
}
return new Promise((resolve, reject) => {
MessageApi.getOne()
.then(result => {
if (result.data.content) {
uni.showModal({
title: result.data.title ? result.data.title : '友情提示',
content: result.data.content,
showCancel: false,
success(res) {
if (res.confirm) {
// 将消息置为已读
MessageApi.readed({'msgId' : result.data.msgId})
.then(result => {
//empty
})
}
}
})
}
})
})
}
export const isWechat = () => {
try {
const ua = window.navigator.userAgent.toLowerCase();
if (ua.match(/micromessenger/i) == 'micromessenger') {
return true;
} else {
return false;
}
} catch (e) {
return false;
}
}
export const wxH5Payment = (data, callback_succ_func, callback_error_func) => {
if (!isWechat()) {
return false;
}
if (typeof WeixinJSBridge == "undefined") {
if (document.addEventListener) {
document.addEventListener('WeixinJSBridgeReady', jsApiCall, false);
} else if (document.attachEvent) {
document.attachEvent('WeixinJSBridgeReady', jsApiCall);
document.attachEvent('onWeixinJSBridgeReady', jsApiCall);
}
} else {
jsApiCall(data, callback_succ_func, callback_error_func);
}
}
export const jsApiCall = (data, callback_succ_func, callback_error_func) => {
//使用原生的避免初始化appid问题
WeixinJSBridge.invoke('getBrandWCPayRequest', {
appId:data['appId'],
timeStamp: data['timeStamp'],
nonceStr: data['nonceStr'], // 支付签名随机串,不长于 32 位
package: data['package'], // 统一支付接口返回的prepay_id参数值提交格式如prepay_id=\*\*\*
signType: data['signType'], // 签名方式,默认为'SHA1',使用新版支付需传入'MD5'
paySign: data['paySign'], // 支付签名
},
function(res) {
var msg = res.err_msg ?res.err_msg :res.errMsg;
//WeixinJSBridge.log(msg);
switch (msg) {
case 'get_brand_wcpay_request:ok': //支付成功时
if(callback_succ_func){
callback_succ_func(res);
}
break;
default: //支付失败时
WeixinJSBridge.log('支付失败!'+msg+',请返回重试.');
if(callback_error_func){
callback_error_func({msg:msg});
}
break;
}
})
}
export const h5Pay = (url, backUrl) => {
// 设置回跳地址,支付完成之后回跳到哪
let redirectUrl ='&redirect_url=' + encodeURIComponent(backUrl);
// 拼接上回跳地址
let linkUrl = url + redirectUrl
const system = uni.getSystemInfoSync()
if (system.platform == 'ios') {
// 如果是iOS平台使用location.hrefiOS里面限制了window.open的使用。
window.location.href = linkUrl;
} else {
window.open(linkUrl);
}
}

View File

@@ -0,0 +1,58 @@
@font-face {
font-family: 'iconfont'; /* Project id 4514721 */
src: url('https://at.alicdn.com/t/c/font_4514721_cvr3z4lc04l.woff2?t=1722241706974') format('woff2'),
url('https://at.alicdn.com/t/c/font_4514721_cvr3z4lc04l.woff?t=1722241706974') format('woff'),
url('https://at.alicdn.com/t/c/font_4514721_cvr3z4lc04l.ttf?t=1722241706974') format('truetype'),
url('https://at.alicdn.com/t/c/font_4514721_cvr3z4lc04l.svg?t=1722241706974#iconfont') format('svg');
}
.iconfont {
font-family: "iconfont" !important;
font-size: 16px;
font-style: normal;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
}
.icon-yanzhengma:before {
content: "\e660";
}
.icon-shoujihao:before {
content: "\e60f";
}
.icon-gouwu:before {
content: "\e899";
}
.icon-fukuan:before {
content: "\e62d";
}
.icon-suo:before {
content: "\e63e";
}
.icon-tuxingyanzhengma:before {
content: "\e799";
}
.icon-fenxiang-post:before {
content: "\e7c5";
}
.icon-download-post:before {
content: "\e63f";
}
.icon-gift:before {
content: "\e682";
}
.icon-copy:before {
content: "\e61c";
}

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,143 @@
import {
mergeConfig,
dispatchRequest,
jsonpRequest
} from "./utils"
export default class request {
constructor(options) {
// 请求公共地址
this.baseUrl = options.baseUrl || "";
// 公共文件上传请求地址
this.fileUrl = options.fileUrl || "";
// 超时时间
this.timeout = options.timeout || 6000;
// 服务器上传图片默认url
this.defaultUploadUrl = options.defaultUploadUrl || "";
// 默认请求头
this.header = options.header || {};
// 默认配置
this.config = options.config || {
isPrompt: true,
load: true,
isFactory: true,
resend: 0
};
}
// post请求
post(url = '', data = {}, options = {}) {
return this.request({
method: "POST",
data: data,
url: url,
...options
});
}
// get请求
get(url = '', data = {}, options = {}) {
return this.request({
method: "GET",
data: data,
url: url,
...options
});
}
// put请求
put(url = '', data = {}, options = {}) {
return this.request({
method: "PUT",
data: data,
url: url,
...options
});
}
// delete请求
delete(url = '', data = {}, options = {}) {
return this.request({
method: "DELETE",
data: data,
url: url,
...options
});
}
// jsonp请求(只限于H5使用)
jsonp(url = '', data = {}, options = {}) {
return this.request({
method: "JSONP",
data: data,
url: url,
...options
});
}
// 接口请求方法
async request(data) {
// 请求数据
let requestInfo,
// 是否运行过请求开始钩子
runRequestStart = false;
try {
if (!data.url) {
throw {
errMsg: "【request】缺失数据url",
statusCode: 0
}
}
// 数据合并
requestInfo = mergeConfig(this, data);
// 代表之前运行到这里
runRequestStart = true;
// 请求前回调
if (this.requestStart) {
let requestStart = this.requestStart(requestInfo);
if (typeof requestStart == "object") {
let changekeys = ["data", "header", "isPrompt", "load", "isFactory"];
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 = {};
if (requestInfo.method == "JSONP") {
requestResult = await jsonpRequest(requestInfo);
} else {
requestResult = await dispatchRequest(requestInfo);
}
// 是否用外部的数据处理方法
if (requestInfo.isFactory && this.dataFactory) {
// 数据处理
let result = await this.dataFactory({
...requestInfo,
response: requestResult
});
return Promise.resolve(result);
} else {
return Promise.resolve(requestResult);
}
} catch (err) {
this.requestError && this.requestError(err);
return Promise.reject(err);
} finally {
// 如果请求开始未运行到,请求结束也不运行
if (runRequestStart) {
this.requestEnd && this.requestEnd(requestInfo);
}
}
}
}

View File

@@ -0,0 +1,102 @@
// 获取合并的数据
export const mergeConfig = (_this, options) => {
//判断url是不是链接
let urlType = /^(http|https):\/\//.test(options.url);
let config = Object.assign({
timeout: _this.timeout
}, _this.config, options);
if (options.method == "FILE") {
config.url = urlType ? options.url : _this.fileUrl + options.url;
} else {
config.url = urlType ? options.url : _this.baseUrl + options.url;
}
//请求头
if (options.header) {
config.header = Object.assign({}, _this.header, options.header);
} else {
config.header = Object.assign({}, _this.header);
}
return config;
}
// 请求
export const dispatchRequest = (requestInfo) => {
return new Promise((resolve, reject) => {
let requestAbort = true;
let requestData = {
url: requestInfo.url,
header: requestInfo.header, //加入请求头
success: (res) => {
requestAbort = false;
resolve(res);
},
fail: (err) => {
requestAbort = false;
if (err.errMsg == "request:fail abort") {
reject({
errMsg: "请求超时,请重新尝试",
statusCode: 0,
});
} else {
reject(err);
}
}
};
//请求类型
if (requestInfo.method) {
requestData.method = requestInfo.method;
}
if (requestInfo.data) {
requestData.data = requestInfo.data;
}
// #ifdef MP-WEIXIN || MP-ALIPAY
if (requestInfo.timeout) {
requestData.timeout = requestInfo.timeout;
}
// #endif
if (requestInfo.dataType) {
requestData.dataType = requestInfo.dataType;
}
// #ifndef APP-PLUS || MP-ALIPAY
if (requestInfo.responseType) {
requestData.responseType = requestInfo.responseType;
}
// #endif
// #ifdef H5
if (requestInfo.withCredentials) {
requestData.withCredentials = requestInfo.withCredentials;
}
// #endif
let requestTask = uni.request(requestData);
setTimeout(() => {
if (requestAbort) {
requestTask.abort();
}
}, requestInfo.timeout)
})
}
// jsonp请求
export const jsonpRequest = (requestInfo) => {
return new Promise((resolve, reject) => {
let dataStr = '';
Object.keys(requestInfo.data).forEach(key => {
dataStr += key + '=' + requestInfo.data[key] + '&';
});
//匹配最后一个&并去除
if (dataStr !== '') {
dataStr = dataStr.substr(0, dataStr.lastIndexOf('&'));
}
requestInfo.url = requestInfo.url + '?' + dataStr;
let callbackName = "callback" + Math.ceil(Math.random() * 1000000);
// #ifdef H5
window[callbackName] = (data) => {
resolve(data);
}
let script = document.createElement("script");
script.src = requestInfo.url + "&callback=" + callbackName;
document.head.appendChild(script);
// 及时删除防止加载过多的JS
document.head.removeChild(script);
// #endif
});
}

View File

@@ -0,0 +1,205 @@
/**
* request插件地址https://ext.dcloud.net.cn/plugin?id=822
*/
import store from '@/store'
import request from './request'
import config from '@/config'
import { isWechat } from '../app';
// 后端api地址
const baseURL = config.apiUrl;
const merchantNo = config.merchantNo;
// 可以new多个request来支持多个域名请求
const $http = new request({
// 接口请求地址
baseUrl: baseURL,
// 服务器本地上传文件地址
fileUrl: baseURL,
// 服务器上传图片默认url
defaultUploadUrl: 'clientApi/file/upload',
// 设置请求头如果使用报错跨域问题可能是content-type请求类型和后台那边设置的不一致
header: {
'content-type': 'application/json;charset=utf-8'
},
// 请求超时时间, 单位ms默认300000
timeout: 300000,
// 默认配置(可不写)
config: {
// 是否自动提示错误
isPrompt: true,
// 是否显示加载动画
load: true,
// 是否使用数据工厂
isFactory: true
}
})
// 当前接口请求数
let requestNum = 0
// 请求开始拦截器
$http.requestStart = options => {
if (options.load) {
if (requestNum <= 0) {
// 打开加载动画
uni.showLoading({
title: '加载中',
mask: true
})
}
requestNum += 1
}
// 图片上传大小限制
if (options.method == "FILE" && options.maxSize) {
// 文件最大字节: options.maxSize 可以在调用方法的时候加入参数
const maxSize = options.maxSize
for (let item of options.files) {
if (item.size > maxSize) {
setTimeout(() => {
uni.showToast({
title: "图片过大,请重新上传",
icon: "none"
})
}, 10)
return false
}
}
}
// 请求前加入当前终端
options.header['platform'] = store.getters.platform ? String(store.getters.platform) : ''
// 请求前加入Token
options.header['Access-Token'] = store.getters.token ? String(store.getters.token) : ''
// 商户号
options.header['merchantNo'] = uni.getStorageSync("merchantNo") ? uni.getStorageSync("merchantNo") : merchantNo;
// 店铺ID
options.header['storeId'] = uni.getStorageSync("storeId") ? uni.getStorageSync("storeId") : 0;
options.header['latitude'] = uni.getStorageSync("latitude") ? uni.getStorageSync("latitude") : '';
options.header['longitude'] = uni.getStorageSync("longitude") ? uni.getStorageSync("longitude") : '';
options.header['isWechat'] = isWechat() ? 'Y' : 'N';
// return false 表示请求拦截,不会继续请求
return options
}
// 请求结束
$http.requestEnd = options => {
// 判断当前接口是否需要加载动画
if (options.load) {
requestNum = requestNum - 1
if (requestNum <= 0) {
uni.hideLoading()
}
}
}
// 登录弹窗次数
let loginPopupNum = 0
// 所有接口数据处理(可在接口里设置不调用此方法)
// 此方法需要开发者根据各自的接口返回类型修改,以下只是模板
$http.dataFactory = async res => {
// console.log("接口请求数据", {
// url: res.url,
// resolve: res.response,
// header: res.header,
// data: res.data,
// method: res.method,
// })
if (!res.response.statusCode || res.response.statusCode != 200) {
// 返回错误的结果(catch接受数据)
return Promise.reject({
statusCode: res.response.statusCode,
// errMsg: "数据工厂验证不通过"
errMsg: 'http状态码错误'
})
}
let httpData = res.response.data
if (typeof httpData == "string") {
try {
httpData = JSON.parse(httpData)
} catch {
httpData = false
}
}
if (httpData === false || typeof httpData !== 'object') {
// 返回错误的结果(catch接受数据)
return Promise.reject({
statusCode: res.response.statusCode,
errMsg: "返回数据验证不通过"
})
}
/*********以下只是模板(及共参考),需要开发者根据各自的接口返回类型修改*********/
// 判断数据是否请求成功
// result.code [ 200正常 5000有错误 1001未登录 4003没有权限访问 ]
// 判断是否需要登录
if (httpData.code == 1001) {
// 1001也有可能是后端登录态到期, 所以要清空本地的登录状态
store.dispatch('Logout')
// 弹窗告诉用户去登录
if (loginPopupNum <= 0) {
loginPopupNum++
uni.showModal({
title: '温馨提示',
content: '此时此刻需要您登录喔~',
confirmText: "去登录",
cancelText: "再逛会",
success: res => {
loginPopupNum--
if (res.confirm) {
uni.navigateTo({
url: "/pages/login/index"
})
}
}
})
}
// 返回错误的结果(catch接受数据)
return Promise.reject({
statusCode: 0,
errMsg: httpData.message,
result: httpData
})
}
// 其他错误提示
else if (httpData.status == 5000) {
if (res.isPrompt) {
setTimeout(() => {
uni.showToast({
title: httpData.message,
icon: "none",
duration: 2500
}, 10)
})
}
// 返回错误的结果(catch接受数据)
return Promise.reject({
statusCode: 0,
errMsg: httpData.message,
result: httpData
})
} else {
// 返回正确的结果(then接受数据)
return Promise.resolve(httpData)
}
/*********以上只是模板(及共参考),需要开发者根据各自的接口返回类型修改*********/
}
// 错误回调
$http.requestError = e => {
if (e.statusCode === 0) {
throw e
} else {
setTimeout(() => {
uni.showToast({
title: `网络请求出错:${e.errMsg}`,
icon: "none",
duration: 2500
})
})
}
}
export default $http

View File

@@ -0,0 +1,7 @@
/***************纯粹的数据请求如果使用这种可以删除掉fileUpload.js******************/
// import request from "./core/request.js";
// export default request;
/********数据请求同时继承了文件上传(包括七牛云上传)************/
import upload from "./upload/upload"
export default upload

View File

@@ -0,0 +1,453 @@
# request请求、配置简单、批量上传图片、视频、超强适应性支持多域名请求
1. 配置简单、源码清晰注释多、适用于一项目多域名请求、第三方请求、七牛云图片上传、本地服务器图片上传等等
2. 支持请求`get``post``put``delete`
3. 自动显示请求加载动画(可单个接口关闭)
4. 全局`api`数据处理函数,只回调请求正确的数据(可单个接口关闭)
5. 未登录或登录失效自动拦截并调用登录方法(可单个接口关闭)
6. 全局自动提示接口抛出的错误信息(可单个接口关闭)
7. 支持 Promise
8. 支持拦截器
9. 支持七牛云文件(图片、视频)批量上传
10. 支持本地服务器文件(图片、视频)批量上传
11. 支持上传文件拦截过滤
12. 支持上传文件进度监听
13. 支持上传文件单张成功回调
| `QQ交流群(607391225)` | `微信交流群(加我好友备注"进群"` |
| ----------------------------|--------------------------- |
|![QQ交流群](http://qn.kemean.cn//upload/202004/14/15868301778472k7oubi6.png)|![微信交流群](https://qn.kemean.cn/upload/202010/13/weiXin_group_code.jpg)|
| QQ群号607391225 |微信号zhou0612wei|
### [点击跳转-插件示例](https://ext.dcloud.net.cn/plugin?id=2009)
### [点击跳转-5年的web前端开源的uni-app快速开发模板-下载看文档](https://ext.dcloud.net.cn/plugin?id=2009)
### 常见问题
1.接口请求成功了没有返回数据或者数据是走的catch回调
答:`requestConfig.js` 请求配置文件里面,有一个`$http.dataFactory`方法,里面写的只是参考示例,`此方法需要开发者根据各自的接口返回类型修改`
2.官方的方法有数据,本插件方法请求报错跨域问题
答:`requestConfig.js` 请求配置文件里面,`header`请求头设置的`content-type`请求类型需求和后台保持一致
3.登录后用户`token`怎么设置?
答:`requestConfig.js` 请求配置文件里面,`$http.requestStart`请求开始拦截器里面设置
4.怎么判断上传的文件(图片)太大?怎么过滤掉太大的文件(图片)?
答:`requestConfig.js` 请求配置文件里面,`$http.requestStart`请求开始拦截器里面设置
5.接口请求成功了,一直提示“网络错误,请检查一下网络”?
答:`requestConfig.js` 请求配置文件里面,有一个`$http.dataFactory`方法,里面写的只是参考示例,`此方法需要开发者根据各自的接口返回类型修改`
### 本次更新注意事项
1. 所有的headers都改成了header和官方统一
2. 七牛云的获取token等信息提取到了`requestConfig.js`文件,参考如下
```
// 添加获取七牛云token的方法
$http.getQnToken = function(callback){
//该地址需要开发者自行配置(每个后台的接口风格都不一样)
$http.get("api/kemean/aid/qn_upload").then(data => {
/*
*接口返回参数:
*visitPrefix:访问文件的域名
*token:七牛云上传token
*folderPath:上传的文件夹
*region: 地区 默认为SCN
*/
callback({
visitPrefix: data.visitPrefix,
token: data.token,
folderPath: data.folderPath,
region: "SCN"
});
});
}
```
### 文件说明
1. `request => core` 请求方法的目录
2. `request => core => request.js` 请求方法的class文件
3. `request => core => utils.js` 请求方法的源码文件
4. `request => upload` 上传方法的目录
5. `request => upload => upload.js` 上传方法的class文件
6. `request => upload => utils.js` 上传方法源码文件
7. `request => upload => qiniuUploader.js` 七牛云官方上传文件
8. `request => index.js` 输出方法的文件
9. `requestConfig.js` 请求配置文件(具体看代码)
### 在main.js引入并挂在Vue上
```
import $http from '@/zhouWei-request/requestConfig';
Vue.prototype.$http = $http;
```
### `requestConfig.js`配置说明requestConfig.js有配置示例
```
import request from "@/plugins/request";
//可以new多个request来支持多个域名请求
let $http = new request({
//接口请求地址
baseUrl: "https://twin-ui.com/", //示例域名,请自行设计
//服务器本地上传文件地址
fileUrl: "https://twin-ui.com/", //示例域名,请自行设计
// 服务器上传图片默认url
defaultUploadUrl: "clientApi/file/upload",
//设置请求头如果使用报错跨域问题可能是content-type请求类型和后台那边设置的不一致
header: {
'Content-Type': 'application/json;charset=UTF-8'
},
// 请求超时时间默认6000
timeout: 6000,
// 默认配置(可不写)
config: {
// 是否自动提示错误
isPrompt: true,
// 是否显示加载动画
load: true,
// 是否使用数据工厂
isFactory: true,
// ... 可写更多配置
}
});
//当前接口请求数
let requestNum = 0;
//请求开始拦截器
$http.requestStart = function(options) {
if (options.load) {
if (requestNum <= 0) {
//打开加载动画
uni.showLoading({
title: '加载中',
mask: true
});
}
requestNum += 1;
}
// 图片上传大小限制
if (options.method == "FILE" && options.maxSize) {
// 文件最大字节: options.maxSize 可以在调用方法的时候加入参数
let maxSize = options.maxSize;
for (let item of options.files) {
if (item.size > maxSize) {
setTimeout(() => {
uni.showToast({
title: "图片过大,请重新上传",
icon: "none"
});
}, 500);
return false;
}
}
}
//请求前加入token
options.header['token'] = "你的项目登录token";
return options; // return false 表示请求拦截,不会继续请求
}
//请求结束
$http.requestEnd = function(options) {
//判断当前接口是否需要加载动画
if (options.load) {
requestNum = requestNum - 1;
if (requestNum <= 0) {
uni.hideLoading();
}
}
}
//所有接口数据处理(可在接口里设置不调用此方法)
//此方法需要开发者根据各自的接口返回类型修改,以下只是模板
$http.dataFactory = async function(res) {
console.log("接口请求数据", {
url: res.url,
resolve: res.response,
header: res.header,
data: res.data,
method: res.method,
});
if (res.response.statusCode && res.response.statusCode == 200) {
let httpData = res.response.data;
if (typeof (httpData) == "string") {
httpData = JSON.parse(httpData);
}
//判断数据是否请求成功
if (httpData.success || httpData.code == 200) {
// ---------重点----------返回正确的结果(then接受数据)------------重点------------
return Promise.resolve(httpData.data);
} else {
//其他错误提示
if (res.isPrompt) { // 是否提示
uni.showToast({
title: httpData.info || httpData.msg,
icon: "none",
duration: 3000
});
}
// --------重点---------返回错误的结果(catch接受数据)------------重点------------
return Promise.reject({
statusCode: 0,
errMsg: "【request】" + (httpData.info || httpData.msg)
});
}
} else {
// 返回错误的结果(catch接受数据)
return Promise.reject({
statusCode: res.response.statusCode,
errMsg: "【request】数据工厂验证不通过"
});
}
};
// 错误回调
$http.requestError = function (e) {
if (e.statusCode === 0) {
throw e;
} else {
uni.showToast({
title: "网络错误,请检查一下网络",
icon: "none"
});
}
}
```
### 通用请求方法
```
this.$http.request({
url: 'aid/region',
method: "GET", // POST、GET、PUT、DELETE、JSONP具体说明查看官方文档
data: {pid:0},
timeout: 30000, // 默认 30000 说明:超时时间,单位 ms具体说明查看官方文档
dataType: "json", // 默认 json 说明:如果设为 json会尝试对返回的数据做一次 JSON.parse具体说明查看官方文档
responseType: "text", // 默认 text 说明设置响应的数据类型。合法值text、arraybuffer具体说明查看官方文档
withCredentials: false, // 默认 false 说明跨域请求时是否携带凭证cookies具体说明查看官方文档
isPrompt: true,//(默认 true 说明:本接口抛出的错误是否提示)
load: true,//(默认 true 说明:本接口是否提示加载动画)
header: { //默认 无 说明:请求头
'Content-Type': 'application/json'
},
isFactory: true, //(默认 true 说明本接口是否调用公共的数据处理方法设置false后isPrompt参数将失去作用
}).then(function (response) {
//这里只会在接口是成功状态返回
}).catch(function (error) {
//这里只会在接口是失败状态返回,不需要去处理错误提示
console.log(error);
});
```
### get请求 正常写法
```
this.$http.get('aid/region',{pid:0}).
then(function (response) {
//这里只会在接口是成功状态返回
}).catch(function (error) {
//这里只会在接口是失败状态返回,不需要去处理错误提示
console.log(error);
});
```
### post请求 async写法
```
async request(){
let data = await this.$http.post('aid/region',{pid:0});
console.log(data);
}
```
### 其他功能配置项
```
let data = await this.$http.post(
'http://www.aaa.com/aid/region', //可以直接放链接(将不启用全局定义域名)
{
pid:0
},
{
isPrompt: true,//(默认 true 说明:本接口抛出的错误是否提示)
load: true,//(默认 true 说明:本接口是否提示加载动画)
header: { //默认 无 说明:请求头
'Content-Type': 'application/json'
},
isFactory: true //(默认 true 说明本接口是否调用公共的数据处理方法设置false后isPrompt参数将失去作用
}
);
```
### `requestConfig.js`可以设置服务器上传图片默认url
```
//可以new多个request来支持多个域名请求
let $http = new request({
//服务器本地上传文件地址
fileUrl: base.baseUrl,
// 服务器上传图片默认url
defaultUploadUrl: "api/common/v1/upload_image",
});
```
```
// 上传可以不用传递url使用全局的上传图片url
this.$http.urlImgUpload({
name:"后台接受文件key名称", //默认 file
count:"最大选择数",//默认 9
sizeType:"选择压缩图原图,默认两个都选",//默认 ['original', 'compressed']
sourceType:"选择相机拍照或相册上传 默认两个都选",//默认 ['album','camera']
data:"而外参数" //可不填,
});
// 上传可以不用传递url使用全局的上传图片url
this.$http.urlVideoUpload({
sourceType:"选择相机拍照或相册上传 默认两个都选",//默认 ['album','camera']
compressed:"是否压缩所选的视频源文件,默认值为 true需要压缩",//默认 false
maxDuration: "拍摄视频最长拍摄时间,单位秒。最长支持 60 秒", //默认 60
camera: '前置还是后置摄像头', //'front'、'back',默认'back'
name:"后台接受文件key名称", //默认 file
data:"而外参数" //可不填,
});
// 上传可以不用传递url使用全局的上传图片url
this.$http.urlFileUpload({
files: [], // 必填 临时文件路径 格式: [{path: "图片地址"}]
data:"向服务器传递的参数", //可不填
name:"后台接受文件key名称", //默认 file
});
```
### 本地服务器图片上传(支持多张上传)
```
this.$http.urlImgUpload('flie/upload',{
name:"后台接受文件key名称", //默认 file
count:"最大选择数",//默认 9
sizeType:"选择压缩图原图,默认两个都选",//默认 ['original', 'compressed']
sourceType:"选择相机拍照或相册上传 默认两个都选",//默认 ['album','camera']
data:"而外参数" //可不填,
isPrompt: true,//(默认 true 说明:本接口抛出的错误是否提示)
load: true,//(默认 true 说明:本接口是否提示加载动画)
header: { //默认 无 说明:请求头
'Content-Type': 'application/json'
},
isFactory: true, //(默认 true 说明本接口是否调用公共的数据处理方法设置false后isPrompt参数奖失去作用
maxSize: 300000, //(默认 无 说明:上传的文件最大字节数限制,默认不限制)
onSelectComplete: res => {
console.log("选择完成返回:",res);
},
onEachUpdate: res => {
console.log("单张上传成功返回:",res);
},
onProgressUpdate: res => {
console.log("上传进度返回:",res);
}
}).then(res => {
console.log("全部上传完返回结果:",res);
});
```
### 本地服务器视频上传
```
this.$http.urlVideoUpload('flie/upload',{
sourceType:"选择相机拍照或相册上传 默认两个都选",//默认 ['album','camera']
compressed:"是否压缩所选的视频源文件,默认值为 true需要压缩",//默认 false
maxDuration: "拍摄视频最长拍摄时间,单位秒。最长支持 60 秒", //默认 60
camera: '前置还是后置摄像头', //'front'、'back',默认'back'
name:"后台接受文件key名称", //默认 file
data:"而外参数" //可不填,
isPrompt: true,//(默认 true 说明:本接口抛出的错误是否提示)
load: true,//(默认 true 说明:本接口是否提示加载动画)
header: { //默认 无 说明:请求头
'Content-Type': 'application/json'
},
isFactory: true, //(默认 true 说明本接口是否调用公共的数据处理方法设置false后isPrompt参数奖失去作用
maxSize: 300000, //(默认 无 说明:上传的文件最大字节数限制,默认不限制)
onProgressUpdate: res => {
console.log("上传进度返回:",res);
},
onSelectComplete: res => {
console.log("选择完成返回:",res);
},
}).then(res => {
console.log("全部上传完返回结果:",res);
});
```
### 本地服务器文件上传(支持多张上传)
```
this.$http.urlFileUpload("flie/upload",{
files: [], // 必填 临时文件路径 格式: [{path: "图片地址"}]
data:"向服务器传递的参数", //可不填
name:"后台接受文件key名称", //默认 file
isPrompt: true,//(默认 true 说明:本接口抛出的错误是否提示)
load: true,//(默认 true 说明:本接口是否提示加载动画)
header: { //默认 无 说明:请求头
'Content-Type': 'application/json'
},
isFactory: true, //(默认 true 说明本接口是否调用公共的数据处理方法设置false后isPrompt参数奖失去作用
maxSize: 300000, //(默认 无 说明:上传的文件最大字节数限制,默认不限制)
onEachUpdate: res => {
console.log("单张上传成功返回:",res);
},
onProgressUpdate: res => {
console.log("上传进度返回:",res);
}
}).then(res => {
console.log("全部上传完返回结果:",res);
});
```
### 七牛云图片上传(支持多张上传)
```
this.$http.qnImgUpload({
count:"最大选择数", // 默认 9
sizeType:"选择压缩图原图,默认两个都选", // 默认 ['original', 'compressed']
sourceType:"选择相机拍照或相册上传 默认两个都选", // 默认 ['album','camera']
load: true, //(默认 true 说明:本接口是否提示加载动画)
maxSize: 300000, //(默认 无 说明:上传的文件最大字节数限制,默认不限制)
onSelectComplete: res => {
console.log("选择完成返回:",res);
},
onEachUpdate: res => {
console.log("单张上传成功返回:",res);
},
onProgressUpdate: res => {
console.log("上传进度返回:",res);
}
}).then(res => {
console.log("全部上传完返回结果:",res);
});
```
### 七牛云视频上传
```
this.$http.qnVideoUpload({
sourceType:"选择相机拍照或相册上传 默认两个都选",//默认 ['album','camera']
compressed:"是否压缩所选的视频源文件,默认值为 true需要压缩",//默认 false
maxDuration: "拍摄视频最长拍摄时间,单位秒。最长支持 60 秒", //默认 60
camera: '前置还是后置摄像头', //'front'、'back',默认'back'
load: true,//(默认 true 说明:本接口是否提示加载动画)
maxSize: 300000, //(默认 无 说明:上传的文件最大字节数限制,默认不限制)
onSelectComplete: res => {
console.log("选择完成返回:",res);
},
onProgressUpdate: res => {
console.log("上传进度返回:",res);
}
}).then(res => {
console.log("全部上传完返回结果:",res);
});
```
### 七牛云文件上传(支持多张上传)
```
this.$http.qnFileUpload(
{
files:[], // 必填 临时文件路径 格式: [{path: "图片地址"}]
load: true, //(默认 true 说明:本接口是否提示加载动画)
maxSize: 300000, //(默认 无 说明:上传的文件最大字节数限制,默认不限制)
onEachUpdate: res => {
console.log("单张上传成功返回:",res);
},
onProgressUpdate: res => {
console.log("上传进度返回:",res);
}
}).then(res => {
console.log("全部上传完返回结果:",res);
});
```
### jsonp 跨域请求只支持H5
```
let data = await this.$http.jsonp('http://www.aaa.com/aid/region',{pid:0}, {
isFactory: false, //(默认 true 说明本接口是否调用公共的数据处理方法设置false后isPrompt参数奖失去作用
});
```

View File

@@ -0,0 +1,169 @@
// created by gpake
(function () {
var config = {
qiniuRegion: '',
qiniuImageURLPrefix: '',
qiniuUploadToken: '',
qiniuUploadTokenURL: '',
qiniuUploadTokenFunction: null,
qiniuShouldUseQiniuFileName: false
}
module.exports = {
init: init,
upload: upload,
}
// 在整个程序生命周期中,只需要 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 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)
})
cancelTask && cancelTask(() => {
uploadTask.abort()
})
}
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) {
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;
}
})();

View File

@@ -0,0 +1,208 @@
import request from "./../core/request.js";
const {
chooseImage,
chooseVideo,
qiniuUpload,
urlUpload
} = require("./utils");
import {
mergeConfig
} from "./../core/utils.js";
export default class fileUpload extends request {
constructor(props) {
// 调用实现父类的构造函数
super(props);
}
//七牛云上传图片
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 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 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 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);
}
}
}
}

View File

@@ -0,0 +1,288 @@
const qiniuUploader = require("./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 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 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(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);
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));
});
}
// #-endif
} else {
reject({
errMsg: "files 必须是数组类型",
statusCode: 0
});
}
});
}

View File

@@ -0,0 +1,86 @@
/**
* 缓存数据优化
* const storage = require('@/utils/storage');
* import storage from '@/utils/storage'
* 使用方法 【
* 一、设置缓存
* string storage.set('k', 'string你好啊');
* json storage.set('k', { "b": "3" }, 2);
* array storage.set('k', [1, 2, 3]);
* boolean storage.set('k', true);
* 二、读取缓存
* 默认值 storage.get('k')
* string storage.get('k', '你好')
* json storage.get('k', { "a": "1" })
* 三、移除/清理
* 移除: storage.remove('k');
* 清理storage.clear();
* 】
* @type {String}
*/
const postfix = '_expiry' // 缓存有效期后缀
module.exports = {
/**
* 设置缓存
* @param {[type]} k [键名]
* @param {[type]} v [键值]
* @param {[type]} t [时间、单位秒]
*/
set(k, v, t) {
uni.setStorageSync(k, v)
const seconds = parseInt(t)
if (seconds > 0) {
let timestamp = Date.parse(new Date())
timestamp = timestamp / 1000 + seconds
uni.setStorageSync(k + postfix, timestamp + '')
} else {
uni.removeStorageSync(k + postfix)
}
},
/**
* 获取缓存
* @param {[type]} k [键名]
* @param {[type]} def [获取为空时默认]
*/
get(k, def) {
const deadtime = parseInt(uni.getStorageSync(k + postfix))
if (deadtime) {
if (parseInt(deadtime) < Date.parse(new Date()) / 1000) {
if (def) {
return def
} else {
return false
}
}
}
const res = uni.getStorageSync(k)
if (res) {
return res
}
if (def == undefined || def == "") {
def = false
}
return def
},
/**
* 删除指定缓存
* @param {Object} k
*/
remove(k) {
uni.removeStorageSync(k)
uni.removeStorageSync(k + postfix)
},
/**
* 清理所有缓存
* @return {[type]} [description]
*/
clear() {
uni.clearStorageSync()
}
}

181
fuintUniapp/utils/util.js Normal file
View File

@@ -0,0 +1,181 @@
/**
* 工具类
*/
/**
* 格式化日期格式 (用于兼容ios Date对象)
*/
export const formatDate = (time) => {
// 将xxxx-xx-xx的时间格式转换为 xxxx/xx/xx的格式
return time.replace(/\-/g, "/");
}
/**
* 对象转URL
* @param {object} obj
*/
export const urlEncode = (obj = {}) => {
const result = []
for (const key in obj) {
const item = obj[key]
if (!item) {
continue
}
if (isArray(item)) {
item.forEach(val => {
result.push(key + '=' + val)
})
} else {
result.push(key + '=' + item)
}
}
return result.join('&')
}
/**
* 遍历对象
*/
export const objForEach = (obj, callback) => {
Object.keys(obj).forEach((key) => {
callback(obj[key], key)
});
}
/**
* 是否在数组内
*/
export const inArray = (search, array) => {
for (var i in array) {
if (array[i] == search) return true
}
return false
}
/**
* 对Date的扩展将 Date 转化为指定格式的String
* 月(Y)、月(m)、日(d)、小时(H)、分(M)、秒(S) 可以用 1-2 个占位符,
* 例子:
* dateFormat('YYYY-mm-dd HH:MM:SS', new Date()) ==> 2020-01-01 08:00:00
*/
export const dateFormat = (fmt, date) => {
const opt = {
"Y+": date.getFullYear().toString(), // 年
"m+": (date.getMonth() + 1).toString(), // 月
"d+": date.getDate().toString(), // 日
"H+": date.getHours().toString(), // 时
"M+": date.getMinutes().toString(), // 分
"S+": date.getSeconds().toString() // 秒
// 有其他格式化字符需求可以继续添加,必须转化成字符串
};
let ret
for (let k in opt) {
ret = new RegExp("(" + k + ")").exec(fmt)
if (ret) {
fmt = fmt.replace(ret[1], (ret[1].length == 1) ? (opt[k]) : (opt[k].padStart(ret[1].length, "0")))
};
};
return fmt
}
/**
* 判断是否为空对象
* @param {*} object 源对象
*/
export const isEmptyObject = (object) => {
return Object.keys(object).length === 0
}
/**
* 判断是否为对象
* @param {*} object
*/
export const isObject = (object) => {
return Object.prototype.toString.call(object) === '[object Object]'
}
/**
* 判断是否为数组
* @param {*} array
*/
export const isArray = (array) => {
return Object.prototype.toString.call(array) === '[object Array]'
}
/**
* 判断是否为空
* @param {*} object 源对象
*/
export const isEmpty = (value) => {
if (isArray(value)) {
return value.length === 0
}
if (isObject(value)) {
return isEmptyObject(value)
}
return !value
}
/**
* 对象深拷贝
* @param {*} obj 源对象
*/
export const cloneObj = (obj) => {
let newObj = obj.constructor === Array ? [] : {};
if (typeof obj !== 'object') {
return;
}
for (let i in obj) {
newObj[i] = typeof obj[i] === 'object' ? cloneObj(obj[i]) : obj[i];
}
return newObj
}
// 节流函数
// 思路: 第一次先设定一个变量true
// 第二次执行这个函数时会判断变量是否true
// 是则返回。当第一次的定时器执行完函数最后会设定变量为flase。
// 那么下次判断变量时则为flase函数会依次运行。
export function throttle(fn, delay = 100) {
// 首先设定一个变量在没有执行我们的定时器时为null
var timer = null
return function() {
// 当我们发现这个定时器存在时,则表示定时器已经在运行中,需要返回
if (timer) return
timer = setTimeout(() => {
fn.apply(this, arguments)
timer = null
}, delay)
}
}
// 防抖函数
// 首次运行时把定时器赋值给一个变量, 第二次执行时,
// 如果间隔没超过定时器设定的时间则会清除掉定时器,
// 重新设定定时器, 依次反复, 当我们停止下来时,
// 没有执行清除定时器, 超过一定时间后触发回调函数。
// 参考文档https://segmentfault.com/q/1010000021145192
export function debounce(fn, delay) {
let timer
return function() {
const that = this
const _args = arguments // 存一下传入的参数
if (timer) {
clearTimeout(timer)
}
timer = setTimeout(function() {
fn.apply(that, _args)
}, delay)
}
}
/**
* 数组交集
* @param {Array} 数组1
* @param {Array} 数组2
* @return {Array}
*/
export const arrayIntersect = (array1, array2) => {
return array1.filter(val => array2.indexOf(val) > -1)
}

View File

@@ -0,0 +1,371 @@
/* iconfont */
@import "/utils/iconfont.scss";
@import "/utils/iconfont-new.scss";
.container, input {
font-family: PingFang-Medium,
PingFangSC-Regular,
Heiti,
Heiti SC,
DroidSans,
DroidSansFallback,
"Microsoft YaHei",
sans-serif;
-webkit-font-smoothing: antialiased;
}
.b-f {
background: #fff;
}
.tf-180 {
-moz-transform: rotate(-180deg);
-ms-transform: rotate(-180deg);
-o-transform: rotate(-180deg);
transform: rotate(-180deg);
}
.tf-90 {
-moz-transform: rotate(90deg);
-ms-transform: rotate(90deg);
-o-transform: rotate(90deg);
transform: rotate(90deg);
}
.dis-block {
display: block;
}
.dis-flex {
display: flex !important;
/* flex-wrap: wrap; */
}
.flex-box {
flex: 1;
}
.flex-dir-row {
flex-direction: row;
}
.flex-dir-column {
flex-direction: column;
}
.flex-x-center {
/* display: flex; */
justify-content: center;
}
.flex-x-between {
justify-content: space-between;
}
.flex-x-around {
justify-content: space-around;
}
.flex-x-end {
justify-content: flex-end;
}
.flex-y-center {
align-items: center;
}
.flex-y-end {
align-items: flex-end;
}
.flex-five {
box-sizing: border-box;
flex: 0 0 50%;
}
.flex-three {
float: left;
width: 33.3%;
}
.flex-two {
float: left;
width: 50%;
}
.flex-four {
box-sizing: border-box;
flex: 0 0 25%;
}
.t-l {
text-align: left;
}
.t-c {
text-align: center;
}
.t-r {
text-align: right;
}
.p-a {
position: absolute;
}
.p-r {
position: relative;
}
.fl {
float: left;
}
.fr {
float: right;
}
.clearfix::after {
clear: both;
content: " ";
display: table;
}
.oh {
overflow: hidden;
}
.tb-lr-center {
display: -webkit-box;
display: -ms-flexbox;
display: flex !important;
-webkit-box-pack: center;
-ms-flex-pack: center;
justify-content: center;
-webkit-box-align: center;
-ms-flex-align: center;
align-items: center;
}
.f-36 {
font-size: 36rpx;
}
.f-34 {
font-size: 34rpx;
}
.f-32 {
font-size: 32rpx;
}
.f-31 {
font-size: 31rpx;
}
.f-30 {
font-size: 30rpx;
}
.f-29 {
font-size: 29rpx;
}
.f-28 {
font-size: 28rpx;
}
.f-26 {
font-size: 26rpx;
}
.f-25 {
font-size: 25rpx;
}
.f-24 {
font-size: 24rpx;
}
.f-22 {
font-size: 22rpx;
}
.f-w {
font-weight: 700;
}
.f-n {
font-weight: 400;
}
.col-f {
color: #fff;
}
.col-3 {
color: #333;
}
.col-6 {
color: #666;
}
.col-7 {
color: #777;
}
.col-8 {
color: #888;
}
.col-9 {
color: #999;
}
.col-m {
color: #fa2209 !important;
}
.col-s {
color: #be0117 !important;
}
.col-green {
color: #0ed339 !important;
}
.cont-box {
padding: 20rpx;
}
.cont-bot {
margin-bottom: 120rpx;
}
.padding-box {
padding: 0 24rpx;
box-sizing: border-box;
}
.pl-12 {
padding-left: 12px;
}
.pr-12 {
padding-right: 12px;
}
.pr-6 {
padding-right: 6px;
}
.m-top4 {
margin-top: 4rpx;
}
.m-top10 {
margin-top: 10rpx;
}
.m-top20 {
margin-top: 25rpx;
}
.m-top30 {
margin-top: 30rpx;
}
.m-l-10 {
margin-left: 10rpx;
}
.m-l-20 {
margin-left: 20rpx;
}
.p-bottom {
padding-bottom: 112rpx;
}
.onelist-hidden {
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
.twolist-hidden {
display: -webkit-box;
word-break: break-all;
text-overflow: ellipsis;
overflow: hidden;
-webkit-box-orient: vertical;
-webkit-line-clamp: 2;
}
.b-r {
border-right: 1rpx solid #eee;
}
.b-b {
border-bottom: 1rpx solid #eee;
}
.b-t {
border-top: 1rpx solid #eee;
}
.ts-1 {
-moz-transition: all 0.1s;
-o-transition: all 0.1s;
transition: all 0.1s;
}
.ts-2 {
-moz-transition: all 0.2s;
-o-transition: all 0.2s;
transition: all 0.2s;
}
.ts-3 {
-moz-transition: all 0.3s;
-o-transition: all 0.3s;
transition: all 0.3s;
}
.ts-5 {
-moz-transition: all 0.5s;
-o-transition: all 0.5s;
transition: all 0.5s;
}
/* 无样式button (用于伪submit) */
.btn-normal {
display: block;
margin: 0;
padding: 0;
line-height: normal;
background: none;
border-radius: 0;
box-shadow: none;
border: none;
font-size: unset;
text-align: unset;
overflow: visible;
color: inherit;
}
.btn-normal:after {
border: none;
}
.btn-normal.button-hover {
color: inherit;
}
button:after {
content: none;
border: none;
}

View File

@@ -0,0 +1,69 @@
/**
* 用户输入内容验证类
*/
// 是否为空
export const isEmpty = (str) => {
return str.trim() == ''
}
/**
* 匹配phone
*/
export const isPhone = (str) => {
const reg = /^((0\d{2,3}-\d{7,8})|(1[3456789]\d{9}))$/
return reg.test(str)
}
/**
* 匹配phone
*/
export const isMobile = (str) => {
const reg = /^(1[3456789]\d{9})$/
return reg.test(str)
}
/**
* 匹配Email地址
*/
export const isEmail = (str) => {
if (str == null || str == "") return false
var result = str.match(/^\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$/)
if (result == null) return false
return true
}
/**
* 判断数值类型,包括整数和浮点数
*/
export const isNumber = (str) => {
if (isDouble(str) || isInteger(str)) return true
return false
}
/**
* 判断是否为正整数(只能输入数字[0-9])
*/
export const isPositiveInteger = (str) => {
return /(^[0-9]\d*$)/.test(str)
}
/**
* 匹配integer
*/
export const isInteger = (str) => {
if (str == null || str == "") return false
var result = str.match(/^[-\+]?\d+$/)
if (result == null) return false
return true
}
/**
* 匹配double或float
*/
export const isDouble = (str) => {
if (str == null || str == "") return false
var result = str.match(/^[-\+]?\d+(\.\d+)?$/)
if (result == null) return false
return true
}