有興趣的小伙伴可以看看上傳圖片的封裝 可以決定要上傳的圖片的大小
全局注冊(cè)方式
import Utils from '@/common/utils/index';
export default {
install: function (Vue) {
Vue.prototype.$utils = new Utils();
}
}
工具類
import uploadFile from '@/request/upload';
/**
* @exports
* 全局工具類
*/
export default class Utils {
constructor() {
console.log("global utils class");
}
/**
* 顯示消息提示框
* @param { String } title 提示的內(nèi)容,長(zhǎng)度與 icon 取值有關(guān)。
* @param { String } position 純文本輕提示顯示位置
* @param { String } icon 圖標(biāo),有效值詳見uniapp官方說明。
* @param { Number } duration 提示的延遲時(shí)間,單位毫秒,默認(rèn):1500
* @param { Boolean } mask 防止觸摸穿透
* @example this.$utils.toast(title);
*/
toast (title, position = 'bottom', icon = 'none', duration = 1500, mask = false) {
uni.showToast({
title,
position,
icon,
duration,
mask
});
}
/**
* 顯示 loading 提示框, 需主動(dòng)調(diào)用
* @param { String } title 提示的文字內(nèi)容,顯示在loading的下方
* @param { Boolean } mask 是否顯示透明蒙層,防止觸摸穿透默認(rèn) true
* @example this.$utils.loading();
*/
loading (title = '正在加載...', mask = true) {
uni.showLoading({
title,
mask
});
}
/**
* 撥打電話
* @param { String } phoneNumber 目標(biāo)號(hào)碼
* @example this.$utils.makePhone(13311112222);
*/
makePhone (phoneNumber) {
uni.makePhoneCall({
phoneNumber
});
}
/**
* 從底部向上彈出操作菜單
* @param { Array } itemList 按鈕的文字?jǐn)?shù)組
* @param { Function } callback 回調(diào)選擇按鈕的索引
* @param { String } textColor 按鈕的文字顏色
* @example this.$utils.showActionSheet(['A','B','C'],index => console.log(index));
*/
showActionSheet (itemList = [], callback, textColor = "#4F4F4F") {
uni.showActionSheet({
itemList,
textColor,
success: function (res) {
callback(res.tapIndex);
},
fail: function (res) {
console.error(res.errMsg);
}
});
}
/**
* 根據(jù)網(wǎng)絡(luò)狀態(tài)提示信息
* @example this.$utils.toastMsgByNetwork();
*/
toastMsgByNetwork () {
uni.getNetworkType({
success (res) {
switch (res.networkType) {
case 'wifi':
this.toast('請(qǐng)求超時(shí),可切換為4g試試哦~');
break;
case '4g':
this.toast('當(dāng)前網(wǎng)絡(luò)狀態(tài)不佳,請(qǐng)稍后再試.');
break;
case '3g':
this.toast('當(dāng)前處在3g狀態(tài),可切換為4g后再試試哦~');
break;
case '2g':
this.toast('當(dāng)前處在2g狀態(tài),可切換為4g后再試試哦~');
break;
case 'ethernet':
this.toast('當(dāng)前處在有線網(wǎng)絡(luò)狀態(tài),可切換為4g后再試試哦~');
break;
case 'unknown':
this.toast('當(dāng)前處在不知名網(wǎng)絡(luò)狀態(tài),可切換為4g后再試試哦~');
break;
case 'none':
this.toast('網(wǎng)絡(luò)走丟了哦~');
break;
default:
this.toast('接口請(qǐng)求超時(shí)間');
break;
}
},
fail (err) {
this.toast('獲取網(wǎng)絡(luò)狀態(tài)失敗');
}
})
}
/**
* upx2px
* @example $utils.upx2px(20) => ≈ 10
* @description 計(jì)算rpx轉(zhuǎn)px
*/
upx2px (num) {
return uni.upx2px(num);
}
/**
* 設(shè)置剪切板內(nèi)容
* @param {*} text
*/
copy (text) {
uni.setClipboardData({
data: text,
success: () => {
uni.hideToast();
this.toast("復(fù)制成功", 'center');
},
fail: () => {
this.toast("復(fù)制失敗", 'center');
console.log(err);
}
});
}
/**
* 封裝圖片上傳
* @param { Array } sourceType 是否使用相機(jī)
* @param { Number } maxSize 當(dāng)前圖片的最大占用內(nèi)存
* @param { Function } callback 回調(diào)當(dāng)前圖片的本地路徑
* @returns { Promise }
* @example this.$utils.chooseImage(['camera'],1,target => {});
*/
chooseImage = (sourceType = ['camera', 'album'], maxSize = 1, callback = null) => {
return new Promise(reslove => uni.chooseImage({
count: 1,
sourceType: sourceType,
sizeType: ['original'],
success: chooseImageRes => {
const tempFilePaths = chooseImageRes.tempFilePaths;
callback != null && callback(tempFilePaths[0]);
/**
* 壓縮文件
* @param { String } imgData.target 壓縮文件路徑
* @param { Number } zipScale 壓縮比例
**/
const zipImage = (imgData, zipScale) => {
const uploadNowImage = imgDataNow => {
uploadFile(`url`, imgDataNow.target).then(data => reslove(data)).catch(err => console.log(err));
}
zipScale == null && uploadNowImage(imgData);
const dstSrc = uni.getSystemInfoSync().platform === 'android' ? `_doc://${new Date().getTime()}.jpg` : `file://${new Date().getTime()}.jpg`;
zipScale && plus.zip.compressImage({
src: imgData.target,
dst: dstSrc,
quality: zipScale
}, res => uploadNowImage(res),
error => this.toast('圖片壓縮失敗'));
}
const { size } = chooseImageRes.tempFiles[0];
const nowSize = parseFloat(size / 1024 / 1024).toFixed(2);
if (nowSize <= maxSize) {
zipImage({ target: tempFilePaths[0], size: size });
} else {
const prevZipSize = parseFloat(maxSize / nowSize).toFixed(2) * 100;
const zipSize = prevZipSize > 10 ? prevZipSize - 10 : prevZipSize;
zipImage({ target: tempFilePaths[0], size: size }, zipSize);
}
},
fail: errData => this.toast(errData)
}))
}
}
上傳圖片
// 導(dǎo)入工具類 并實(shí)例化
import Utils from '@/common/utils/index';
const utils = new Utils();
/**
* @exports
* 封裝上傳
* @param { String } url 上傳接口地址
* @param { String } filePath 本地圖片地址
* @returns { Promise }
*/
export default function (url, filePath, otherData = {}) {
return new Promise((reslove, reject) => {
utils.loading("正在上傳...");
uni.uploadFile({
url: url,
filePath: filePath,
header: {},
formData: otherData,
name: 'file',
success: ({ statusCode, data }) => {
const { code, result, message } = JSON.parse(data);
if (statusCode === 200) {
if (code === 200) {
reslove({ result: result, filePath: filePath });
} else {
utils.toast(message);
reject(null);
}
} else {
utils.toast('網(wǎng)絡(luò)錯(cuò)誤');
reject(null);
}
},
complete: _ => uni.hideLoading(),
fail: ({ errMsg }) => {
if (errMsg === 'request:fail timeout') {
uni.getNetworkType({
success ({ networkType }) {
networkType === 'wifi' && utils.toast('上傳失敗,請(qǐng)檢查您的網(wǎng)絡(luò)或者切換到4G網(wǎng)絡(luò)重試');
networkType === '4g' && utils.toast('上傳失敗,請(qǐng)重試.');
(networkType !== '4g' && networkType !== 'wifi') && utils.toast('上傳失敗,請(qǐng)切換到4G網(wǎng)絡(luò)重試');
reject(null);
},
fail: err => {
utils.toast('獲取網(wǎng)絡(luò)狀態(tài)失敗.');
reject(err);
}
})
} else {
utils.toast('請(qǐng)求失敗.');
reject(null);
}
}
});
})
}