prevention/package_A/page/upload/index.js

253 lines
8.6 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

// package_A/page/upload/index.js
const crypto = require('crypto-js')
import {Base64} from 'js-base64'
import {getOssAuth} from '../../../api/upload.js'
import {confirmOrder} from '../../../api/task.js'
Page({
/**
* 页面的初始数据
*/
data: {
type: 'upload',
form: {},
carNumberList: [],
healthCodeList: [],
formRules: {
carNumberList: {
validator: function (value) {
return value.length!=0;
},
warning: false
},
healthCodeList: {
validator: function (value) {
return value.length!=0;
},
warning: false
}
}
},
onLoad(e) {
if(e.data) {
let data = JSON.parse(e.data)
let carNumberList = [data.carUrl]
let list = data.registerFlowmanVoList || []
let arr = []
if(list.length > 0) {
list.forEach(item=> {
if(item.imageUrl) {
arr.push(item.imageUrl)
}
})
}
let healthCodeList = arr
this.setData({type: 'detail', carNumberList, healthCodeList})
}
if(this.data.type === 'upload') {
this.getOssAuthForm()
}
},
// 图片预览
previewImage(e) {
let type = e.currentTarget.dataset.type
let str = type + 'List'
wx.previewImage({
urls: this.data[str],
})
},
validate(name) {
let formRules = this.data.formRules;
let validator = formRules[name].validator
let result
result = validator ? !validator(this.data[name]) : false
formRules[name].warning = result
this.setData({formRules})
return result
},
// 表单验证
validateForm() {
return new Promise((resolve, reject) => {
try {
let formRules = this.data.formRules;
let result = false;
for (let key in formRules) {
let temp = this.validate(key)
if (temp) {
result = temp
}
}
resolve(!result)
} catch (e) {
reject(e)
}
})
},
/* 获取图片上传鉴权 */
getOssAuthForm() {
let that = this
getOssAuth().then((res)=> {
let client = {
region: 'oss-cn-shanghai',
secure: true,
accessKeyId: res.accessKeyId,
accessKeySecret: res.accessKeySecret,
securityToken: res.securityToken,
bucket: 'ta-tech-image'
}
// 计算签名
function computeSignature(accessKeySecret, canonicalString) {
return crypto.enc.Base64.stringify(crypto.HmacSHA1(canonicalString, accessKeySecret));
}
const date = new Date();
date.setHours(date.getHours() + 1);
const policyText = {
expiration: date.toISOString(), // 设置policy过期时间。
conditions: [
// 限制上传大小。
["content-length-range", 0, 1024 * 1024 * 1024],
],
};
// 获取签名
const policy = Base64.encode(JSON.stringify(policyText)) // policy必须为base64的string。
const signature = computeSignature(client.accessKeySecret, policy)
let ossForm = that.data.ossForm
ossForm = {
OSSAccessKeyId: client.accessKeyId,
signature,
policy,
SecurityToken: client.securityToken
}
that.setData({ossForm})
}).catch(e=> {
console.log(e);
})
},
/* 上传图片 */
uploadImages(e){
let type = e.currentTarget.dataset.type
let limit = e.currentTarget.dataset.limit
wx.chooseImage({
count: limit - this.data[type + 'List'].length, // 最多可以选择的图片张数默认9
mediaType: ['image'], // 图片
sizeType: ['compressed'], // original 原图compressed 压缩图,默认二者都有
sourceType: ['album', 'camera'], // album 从相册选图camera 使用相机,默认二者都有
success:(res) =>{
// success
let str = type+'List'
let imageList = this.data[str].concat(res.tempFilePaths);
if(type === 'carNumber') {
this.setData({carNumberList: imageList})
} else {
this.setData({healthCodeList: imageList})
}
this.validate(type+'List')
},
fail: (e) => {
console.log('取消选择');
}
})
},
// 删除图片
deleteImage(e) {
let type = e.currentTarget.dataset.type
let index = this.getCurrentData(e);
let list = this.data[type+"List"]
list.splice(index, 1)
let str = type + 'List'
if(type === 'carNumber') {
this.setData({carNumberList: list})
} else {
this.setData({healthCodeList: list})
}
this.validate(str)
},
getCurrentData(e) {
return e.currentTarget.dataset.current;
},
/* 取消 */
returnLastPage() {
this.setData({
form: {}
})
wx.navigateBack({
delta: 1,
})
},
/* 表单上传 */
submit(){
this.validateForm().then(res => {
if(res) {
let carNumberList = this.data.carNumberList
let healthCodeList = this.data.healthCodeList
let imageList = carNumberList.concat(healthCodeList)
let ossForm = this.data.ossForm
let temp = []
if (imageList.length > 0) {
wx.showLoading({title:"上传中",mask:true})
temp = imageList.map(item => {
// 设置文件上传路径
const randomString = Math.random().toString(36).slice(2)
const timestamp = new Date().getTime()
const key = `imagedir/${randomString}_${timestamp}.png`
// 上传图片
return new Promise((resolve, reject)=> {
wx.uploadFile({
url: 'https://ta-tech-image.oss-cn-shanghai.aliyuncs.com',
filePath: item,
name: 'file',
formData: {
key,
OSSAccessKeyId: ossForm.OSSAccessKeyId,
signature: ossForm.signature,
policy: ossForm.policy,
'x-oss-security-token': ossForm.SecurityToken
},
success: (res)=> {
if(res.statusCode === 204) {
// 上传成功将图片路径resolve出去
resolve(key)
}
},
fail: (e)=> {
wx.showToast({
title: '图片上传失败',
})
}
})
})
})
Promise.all(temp).then((res)=> {
let form = this.data.form;
form.carUrl = res[0]
res.shift()
form.flowManUrlList = res
// 登记
confirmOrder(form).then(res => {
if (res?.code === 0) {
wx.reLaunch({
url: '/pages/task/task',
})
}
}).catch(e=> {
console.log(e);
}).finally(()=>{
wx.hideLoading();
})
}).catch((e)=> {
wx.hideLoading()
})
}
}
})
}
})