Commit a40d65b7 authored by Damon's avatar Damon

完工图片-异步上传

parent ee3fb5c7
...@@ -3,8 +3,9 @@ import "./../.env.js"; ...@@ -3,8 +3,9 @@ import "./../.env.js";
import { AnalysysAgent } from "@/utils/analysys_paas.js"; import { AnalysysAgent } from "@/utils/analysys_paas.js";
import util from "@/utils/util.js"; import util from "@/utils/util.js";
import login from "@/utils/login.js"; import login from "@/utils/login.js";
import upload from '@/components/upload/task.js'
export default { export default {
globalData: { globalData: {
// 开发环境 // 开发环境
uniEnv: process.uniEnv, uniEnv: process.uniEnv,
// 微信小程序平台编号,空--家维广场,1--自营平台 // 微信小程序平台编号,空--家维广场,1--自营平台
...@@ -45,131 +46,143 @@ export default { ...@@ -45,131 +46,143 @@ export default {
// 授权用户信息 // 授权用户信息
authUserInfo: "", authUserInfo: "",
// 用户入驻信息 // 用户入驻信息
settledInfo: {}, settledInfo: {},
navHeight: 0, //导航栏高度 navHeight: 0, //导航栏高度
rpxScreenHeight: 0,// 照相视框高度 rpxScreenHeight: 0, // 照相视框高度
safeHeight:0, // 安全高度 safeHeight: 0, // 安全高度
//拍照相关数据 //拍照相关数据
photo: { photo: {
product: { product: {
brandId: '', // 品牌id brandId: "", // 品牌id
brandName: '', // 品牌名称 brandName: "", // 品牌名称
classifyId: '', // 分类id classifyId: "", // 分类id
systemId: '', // 系统id systemId: "", // 系统id
}, },
topIndex:0, topIndex: 0,
itemIndex:0, itemIndex: 0,
currentItemLength: 0,//已拍摄照片张数 currentItemLength: 0, //已拍摄照片张数
productList: [], productList: [],
currentItem: null, // 选择的某一项 currentItem: null, // 选择的某一项
setting: null, //自定义设置 setting: null, //自定义设置
waterSetting: null, // 水印设置 waterSetting: null, // 水印设置
allImages: [], allImages: [],
tempPath: { tempPath: {
origin: '', // 缓存拍照图片 origin: "", // 缓存拍照图片
mixWater: '' // 缓存水印拍照图片 mixWater: "", // 缓存水印拍照图片
} },
}, },
}, },
onLaunch: async function () { onLaunch: async function () {
// 应用初始化(全局只触发一次) // 应用初始化(全局只触发一次)
AnalysysAgent.registerSuperProperty("platform", "self-support"); AnalysysAgent.registerSuperProperty("platform", "self-support");
this.getSystemInfo() this.getSystemInfo();
// 版本更新 // 版本更新
await this.updateApp(); await this.updateApp();
// 系统自动登录 // 系统自动登录
await this.autoLogin(); await this.autoLogin();
}, },
onShow: async function () { onShow: async function () {
// 应用启动,或从后台进入前台显示 // 应用启动,或从后台进入前台显示
}, },
onHide: function () { onHide: function () {
// 应用从前台进入后台 // 应用从前台进入后台
}, },
methods: { watch: {
getSystemInfo() { uploadTask: function(newValue, oldValue) {
try { console.log("oldValue, newValue", oldValue, newValue)
let a = wx.getSystemInfoSync(); if(newValue.length > 0) upload.uploadImageTask(this)
}
// this.globalData.platform = systemInfo.platform, this.globalData.pixelRatio = a.pixelRatio, },
// this.globalData.statusBarHeight = a.statusBarHeight, this.globalData.navHeight = a.statusBarHeight / a.screenWidth * 750 + 90, methods: {
// this.globalData.rpxScreenHeight = a.screenHeight / a.screenWidth * 750, this.globalData.screenWidth = a.screenWidth, getSystemInfo() {
// this.globalData.screenHeight = a.screenHeight; try {
this.globalData.navHeight = a.statusBarHeight / a.screenWidth * 750 + 90 let a = wx.getSystemInfoSync();
this.globalData.rpxScreenHeight = a.screenHeight / a.screenWidth * 750
this.globalData.screenHeight = a.screenHeight // this.globalData.platform = systemInfo.platform, this.globalData.pixelRatio = a.pixelRatio,
this.globalData.safeHeight = a.safeArea.bottom // this.globalData.statusBarHeight = a.statusBarHeight, this.globalData.navHeight = a.statusBarHeight / a.screenWidth * 750 + 90,
} catch (a) { // this.globalData.rpxScreenHeight = a.screenHeight / a.screenWidth * 750, this.globalData.screenWidth = a.screenWidth,
} // this.globalData.screenHeight = a.screenHeight;
}, this.globalData.navHeight =
async getBaseInfo(vm, callBack) { (a.statusBarHeight / a.screenWidth) * 750 + 90;
uni.showLoading({ this.globalData.rpxScreenHeight =
title: "加载中……", (a.screenHeight / a.screenWidth) * 750;
}); this.globalData.screenHeight = a.screenHeight;
const res = await vm.$u.api.getSettleBaseInfo(); this.globalData.safeHeight = a.safeArea.bottom;
if (res.code !== 200) { } catch (a) {}
uni.showToast({ },
title: (res && res.message) || "获取基本信息错误", async getBaseInfo(vm, callBack) {
icon: "none", uni.showLoading({
}); title: "加载中……",
return false; });
} const res = await vm.$u.api.getSettleBaseInfo();
if (res.code !== 200) {
vm.$u.vuex('vuex_settled', res.data || null); uni.showToast({
if (!res.data) { title: (res && res.message) || "获取基本信息错误",
return; icon: "none",
} });
if (typeof callBack == "function") { return false;
callBack(vm, res.data); }
}
uni.hideLoading(); vm.$u.vuex("vuex_settled", res.data || null);
return res.data; if (!res.data) {
return;
}
if (typeof callBack == "function") {
callBack(vm, res.data);
}
uni.hideLoading();
return res.data;
}, },
/** /**
* 微信用户自动登录 * 微信用户自动登录
*/ */
async autoLogin() { async autoLogin() {
let that = this; let that = this;
// 如果token不为空,则跳过自动登录 // 如果token不为空,则跳过自动登录
if(that.vuex_token) { if (that.vuex_token) {
return return;
} }
await login.oauth().then(async res => { await login.oauth().then(async (res) => {
if (res.code) { if (res.code) {
let params = { let params = {
code: res.code, code: res.code,
wxAppNo: that.globalData.wxAppNo, // 自营平台小程序 wxAppNo: that.globalData.wxAppNo, // 自营平台小程序
}; };
let result = await that.$u.api.loginWechatAuth(params) let result = await that.$u.api.loginWechatAuth(params);
if (result && result.code == 200 && result.data && result.data.token) { if (
that.setUserData(result.data); result &&
} else { result.code == 200 &&
uni.navigateTo({ result.data &&
url: "pages/login/index" result.data.token
}) ) {
} that.setUserData(result.data);
} else { } else {
uni.showModal({ uni.navigateTo({
title: "登录失败", url: "pages/login/index",
content: "未获取到code", });
}); }
} } else {
}) uni.showModal({
title: "登录失败",
content: "未获取到code",
});
}
});
}, },
setUserData(userInfo) { setUserData(userInfo) {
if (userInfo && userInfo.token) { if (userInfo && userInfo.token) {
// 如果已经登录则直接获取相关信息 // 如果已经登录则直接获取相关信息
this.$u.vuex('vuex_token',userInfo.token); this.$u.vuex("vuex_token", userInfo.token);
this.$u.vuex('vuex_user', userInfo); this.$u.vuex("vuex_user", userInfo);
this.$u.vuex('vuex_wx_uid', userInfo.wxopenid); this.$u.vuex("vuex_wx_uid", userInfo.wxopenid);
} else { } else {
this.$u.vuex('vuex_token', ''); this.$u.vuex("vuex_token", "");
this.$u.vuex('vuex_user', null); this.$u.vuex("vuex_user", null);
this.$u.vuex('vuex_wx_uid', ''); this.$u.vuex("vuex_wx_uid", "");
} }
}, },
......
...@@ -107,21 +107,26 @@ ...@@ -107,21 +107,26 @@
const self = this const self = this
if(type&&type==='photo'){ if(type&&type==='photo'){
// 直接打开相册 // 直接打开相册
let config = { let options = {
options:{ sourceType:['album'],//['album', 'camera']
sourceType:['album'],//['album', 'camera'] count: 3,
count: 3, sizeType: ['compressed']
sizeType: ['compressed']
}
} }
await this.chooseImage('qiniu',config) const value = await this.chooseImg(options)
self.setValue() self.setTmpValue(value)
//await this.chooseImage('qiniu',config)
//self.setValue()
return return
} }
// 使用拍照工具拍摄 // 使用拍照工具拍摄
this.photograph() this.photograph()
this.getWatermark() this.getWatermark()
}, },
setTmpValue(values) {
this.imgList = this.imgList.concat(values)
const dataValue = values.map(v => v.key)
this.valueChange(dataValue)
},
setValue() { setValue() {
const dataValue = [] const dataValue = []
this.imgList.map(item=>{ this.imgList.map(item=>{
...@@ -131,32 +136,35 @@ ...@@ -131,32 +136,35 @@
}, },
closeTake(val) { closeTake(val) {
if(val && val.length > 0){ if(val && val.length > 0){
val.forEach(item=>{ // val.forEach(item=>{
this.imgList.push(item) // this.imgList.push(item)
}) // })
const files = val.map(v => { // const files = val.map(v => {
return { path: v.path } // return { path: v.path }
}) // })
const files = val.map(v => v.path)
this.uploadTakeImg(files) this.uploadTakeImg(files)
// this.setValue() // this.setValue()
} }
this.takeStatus = false this.takeStatus = false
}, },
uploadTakeImg(files) { async uploadTakeImg(files) {
const options = { const value = await this.saveToTask(files)
files:files, // 必填 临时文件路径 格式: [{path: "图片地址"}] this.setTmpValue(value)
load: false, //(默认 true 说明:本接口是否提示加载动画) // const options = {
maxSize: 300000, //(默认 无 说明:上传的文件最大字节数限制,默认不限制) // files:files, // 必填 临时文件路径 格式: [{path: "图片地址"}]
onEachUpdate: res => { // load: false, //(默认 true 说明:本接口是否提示加载动画)
console.log("上传成功返回:",res); // maxSize: 300000, //(默认 无 说明:上传的文件最大字节数限制,默认不限制)
const value = [uploader.qiniuTokenObj.visitPrefix + res.url] // onEachUpdate: res => {
this.valueChange(value) // console.log("上传成功返回:",res);
}, // const value = [uploader.qiniuTokenObj.visitPrefix + res.url]
Update: res => { // this.valueChange(value)
console.log("上传进度返回:",res); // },
} // Update: res => {
} // console.log("上传进度返回:",res);
uploader.qnFileUpload(options) // }
// }
// uploader.qnFileUpload(options)
}, },
prviewImage(item, index) { prviewImage(item, index) {
uni.previewImage({ uni.previewImage({
......
import uploader from '@/plugins/uploader/index.js' import uploader from '@/plugins/uploader/index.js'
const globalUrl = process.uniEnv || {} const globalUrl = process.uniEnv || {}
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 default { export default {
name: 'upload', name: 'upload',
components: {}, components: {},
...@@ -28,6 +42,63 @@ export default { ...@@ -28,6 +42,63 @@ export default {
} }
let res = await uploader.urlFileUpload(options) let res = await uploader.urlFileUpload(options)
}, },
/**
* 存储图片到任务队列
* @param {Array} files 图片路径
*/
async saveToTask(files) {
// 生成key返回,然后把key放到异步上传的任务队列
let lists = []
for (let i = 0; i < files.length; i++) {
const path = files[i]
const row = await this.saveFiles(path)
lists.push(row)
}
const data = this.uploadTask
const saveLists = data.concat(lists)
this.$u.vuex('uploadTask', saveLists)
return lists
},
/**
* 选择图片
* @param {Object} data option
*/
async chooseImg(data){
const self = this
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) {
const lists = self.saveToTask(res.tempFilePaths)
resolve(lists)
},
fail: err => {
console.log("err", err)
}
})
})
},
// 保存图片到本地
saveFiles(path) {
return new Promise((resolve, reject) => {
uni.saveFile({
tempFilePath: path,
success(e) {
const { savedFilePath } = e
const img = {
key: randomChar(10),
path: savedFilePath,
src: ''
}
resolve(img)
},
fail: reject
})
})
},
/** /**
* 上传图片公用组件 * 上传图片公用组件
* @param {Object} type 文件上传方式 * @param {Object} type 文件上传方式
......
import uploader from '@/plugins/uploader/index.js'
export default {
/**
* 执行任务队列
*/
async uploadImageTask(that) {
const uploadTask = that.uploadTask
console.log("uploadTask", uploadTask)
const options = {
files: uploadTask, // 必填 临时文件路径 格式: [{path: "图片地址"}]
load: false, //(默认 true 说明:本接口是否提示加载动画)
maxSize: 300000, //(默认 无 说明:上传的文件最大字节数限制,默认不限制)
onEachUpdate: res => {
console.log("上传成功返回:",res);
const newTask = uploadTask.filter(v => v.key !== res.key)
// that.$u.vuex('uploadTask', newTask)
},
Update: res => {
console.log("上传进度返回:",res);
}
}
uploader.qnFileUpload(options)
},
}
\ No newline at end of file
...@@ -16,7 +16,7 @@ let baseOptions = { ...@@ -16,7 +16,7 @@ let baseOptions = {
// 是否自动提示错误 // 是否自动提示错误
isPrompt: true, isPrompt: true,
// 是否显示加载动画 // 是否显示加载动画
load: true, load: false,
// 是否使用数据工厂 // 是否使用数据工厂
isFactory: true isFactory: true
} }
......
...@@ -91,7 +91,7 @@ export const qiniuUpload = function(requestInfo, qnRes) { ...@@ -91,7 +91,7 @@ export const qiniuUpload = function(requestInfo, qnRes) {
function uploadFile(i) { function uploadFile(i) {
let item = requestInfo.files[i]; let item = requestInfo.files[i];
let updateUrl = randomChar(10, qnRes.folderPath); let updateUrl = item.key //randomChar(10, qnRes.folderPath);
let fileData = { let fileData = {
fileIndex: i, fileIndex: i,
files: requestInfo.files, files: requestInfo.files,
...@@ -124,7 +124,6 @@ export const qiniuUpload = function(requestInfo, qnRes) { ...@@ -124,7 +124,6 @@ export const qiniuUpload = function(requestInfo, qnRes) {
uptoken: qnRes.token, // 由其他程序生成七牛 uptoken uptoken: qnRes.token, // 由其他程序生成七牛 uptoken
uptokenURL: 'UpTokenURL.com/uptoken' // 上传地址 uptokenURL: 'UpTokenURL.com/uptoken' // 上传地址
}, (res) => { }, (res) => {
console.log(requestInfo);
requestInfo.onProgressUpdate && requestInfo.onProgressUpdate(Object.assign({}, fileData, res)); requestInfo.onProgressUpdate && requestInfo.onProgressUpdate(Object.assign({}, fileData, res));
// console.log('上传进度', res.progress) // console.log('上传进度', res.progress)
// console.log('已经上传的数据长度', res.totalBytesSent) // console.log('已经上传的数据长度', res.totalBytesSent)
......
...@@ -12,7 +12,7 @@ try { ...@@ -12,7 +12,7 @@ try {
} }
// 需要永久存储,且下次APP启动需要取出的,在state中的变量名 // 需要永久存储,且下次APP启动需要取出的,在state中的变量名
let saveStateKeys = ['vuex_user', 'vuex_wx_uid', 'vuex_token']; let saveStateKeys = ['vuex_user', 'vuex_wx_uid', 'vuex_token', 'uploadTask'];
// 保存变量到本地存储中 // 保存变量到本地存储中
const saveLifeData = function(key, value) { const saveLifeData = function(key, value) {
...@@ -37,6 +37,8 @@ const store = new Vuex.Store({ ...@@ -37,6 +37,8 @@ const store = new Vuex.Store({
// 入驻信息 // 入驻信息
vuex_settled: null, vuex_settled: null,
vuex_wx_uid: lifeData.vuex_wx_uid || 0, vuex_wx_uid: lifeData.vuex_wx_uid || 0,
// 上传队列
uploadTask: lifeData.uploadTask ? lifeData.uploadTask : []
}, },
mutations: { mutations: {
$uStore(state, payload) { $uStore(state, payload) {
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment