Commit 4eebb2fa by 前端

失败记录缓存本地

1 parent e60e1645
......@@ -9,7 +9,9 @@
<script>
import checkUpdate from "@/uni_modules/uni-upgrade-center-app/utils/check-update-nvue.js";
import { mapState } from "vuex";
import storge from "@/mixin/storge";
export default {
mixins: [storge],
computed: {
...mapState("audio", ["isEnd", "isStart"]),
},
......
......@@ -4,9 +4,11 @@
ref="formRef"
@cancel="cancel"
@confirm="submit"
:cancelBtnText="`${step == 1? '取消' : '上一步'}`"
:confirmBtnText="`${sceneType == 0 ?step == 1? '下一步' : '完成接待': '完成接待'}`"
:title="`${step == 1? '客户信息完善' : '结果反馈'}`"
:cancelBtnText="`${step == 1 ? '取消' : '上一步'}`"
:confirmBtnText="`${
sceneType == 0 ? (step == 1 ? '下一步' : '完成接待') : '完成接待'
}`"
:title="`${step == 1 ? '客户信息完善' : '结果反馈'}`"
:popupW="820"
:maxHeight="820"
:isAutoClose="false"
......@@ -14,23 +16,24 @@
<view name="content">
<template v-if="step == 1">
<template v-if="!check(true)">
<view
class="error-tip"
v-if="errorTip"
>以下信息不能为空,请完善信息后保存</view>
<view
class="pop-tips"
v-else
>{{tips}}</view>
<view class="error-tip" v-if="errorTip"
>以下信息不能为空,请完善信息后保存</view
>
<view class="pop-tips" v-else>{{ tips }}</view>
</template>
<view class="form">
<template v-for="(i, index) in formObject">
<view class="form-item" :key="index">
<view :class="['label', { required: i.required }]">{{
i.label
}}</view>
<view
class="form-item"
:key="index"
:class="[
'value',
{ error: showError(i.key) && i.required },
{ disabled: customerType == 0 },
]"
>
<view :class="['label',{required:i.required}]">{{ i.label }}</view>
<view :class="['value', { error: showError(i.key) && i.required },{disabled:customerType == 0}]">
<template v-if="i.type == 'input'">
<input
:type="i.inputType"
......@@ -44,7 +47,10 @@
</template>
<template v-else>
<view
:class="['select', `${formData[i.key]? '' : 'placeholder'}`]"
:class="[
'select',
`${formData[i.key] ? '' : 'placeholder'}`,
]"
@click="showPopup(i.popKey)"
>
{{ formData[i.key] || i.placeholder }}
......@@ -63,14 +69,30 @@
<template v-else>
<view class="pop-tips">请完善本次接待结果</view>
<view class="choose-box">
<template v-for="(i,index) in resultList">
<template v-for="(i, index) in resultList">
<view
:class="['choose-item', `${i.status == receptionStatus ? i.status == 1 ? 'success' : 'error' : ''}`]"
:class="[
'choose-item',
`${
i.status == receptionStatus
? i.status == 1
? 'success'
: 'error'
: ''
}`,
]"
:key="index"
@click="chooseResult(i.status)"
>
<view :class="['sprite-icon' , `icon-face-${i.status == receptionStatus ? `${i.icon}-active` : i.icon }`]"></view>
{{ i.text}}
<view
:class="[
'sprite-icon',
`icon-face-${
i.status == receptionStatus ? `${i.icon}-active` : i.icon
}`,
]"
></view>
{{ i.text }}
</view>
</template>
</view>
......@@ -79,26 +101,23 @@
</MessageBox>
<car-brands
ref="carBrandListVisible"
@select="handleSelect($event,'carBrandListVisible')"
@select="handleSelect($event, 'carBrandListVisible')"
/>
<employee
ref="employeeBoxVisible"
@select="handleSelect($event,'employeeBoxVisible')"
@select="handleSelect($event, 'employeeBoxVisible')"
/>
<uni-popup
ref="successRef"
type="message"
>
<uni-popup ref="successRef" type="message">
<uni-popup-message
type="success"
message="保存成功"
message="数据保存成功"
:duration="1500"
></uni-popup-message>
</uni-popup>
</view>
</template>
<script type='text/ecmascript-6'>
<script type="text/ecmascript-6">
import Employee from '@/components/Employee.vue'
import CarBrands from '@/components/CarBrands.vue'
import { mapMutations } from "vuex";
......@@ -342,7 +361,7 @@ export default {
}
</script>
<style scoped lang='scss'>
<style scoped lang="scss">
.pop-tips {
background: rgba(44, 102, 247, 0.1);
color: #2c66f7;
......
......@@ -14,6 +14,7 @@ const UPLOAD_STATUS = {
fail: 2,
};
import upload from "@/utils/ossUploadFile/uploadFile.js";
import fileManager from "@/utils/file/FileManager.js";
import { mapMutations, mapState } from "vuex";
import utils from "@/utils/utils.js";
export default {
......@@ -27,6 +28,13 @@ export default {
};
},
mounted() {
// this.checkRecord();
// fileManager.writeFile("123.txt", 555);
// fileManager.readFile("file://123.txt").then((res) => {
// // res 读取的文件内容
// console.log(res);
// });
// 获取当前页面栈数组
const pages = getCurrentPages();
const currentPage = pages[pages.length - 1];
......@@ -124,43 +132,10 @@ export default {
//保存录音记录及其他信息
async uploadVoice(tempFilePath) {
try {
const { shopMerchantId, phone, sceneType } =
uni.$storage.get("userInfo"),
{ customerName, phoneNumber, salesUuid, carModel, staffName } =
this.$store.state.user.customerInfo,
receptionCustomerPaySourceList = this.booksList.map((item) => {
return {
id: item.id,
sourceType: item.id,
sourceUrl: item.imgUrl,
};
}),
{ receptionStartTime, receptionEndTime, endReasonType } =
this.audioInfo,
params = {
carModel,
endReasonType, //原因 1.异常 0.正常
customerName,
phoneNumber,
loginPhone: phone,
salesName: staffName,
salesUuid,
receptionStatus: this.receptionStatus, //接待结果 1.成交 0.战败
const params = Object.assign(this.getParams(), {
recordUrlList: tempFilePath,
receptionStartTime,
receptionEndTime,
receptionCustomerPaySourceList, //1.付款凭证文件路径 2.客户购车发票文件路径 3.客户延保合同文件路径
merchantId: shopMerchantId,
bussinessType: sceneType == 0 ? 1 : 2, // sceneType 0延保 1精品。 bussinessType 1.延保 2.轻改
};
console.log(
customerName,
phoneNumber,
salesUuid,
carModel,
tempFilePath
);
if (customerName && phoneNumber && salesUuid) {
});
if (params.customerName && params.phoneNumber && params.salesUuid) {
uni.$api.commonApi.saveRecCustomer(params).then((res) => {
console.log(res, params);
});
......@@ -195,6 +170,10 @@ export default {
});
}
if (this.audioInfo.audioStatus == "no") {
setTimeout(() => {
uni.hideLoading();
}, 2000);
uni.removeSavedFile({
filePath: res.tempFilePath,
complete: function (res) {
......@@ -203,15 +182,14 @@ export default {
});
return;
}
// const isContinue = this.hasErrorFile();
// if (isContinue) {
// this.handleErrorFile(res.tempFilePath);
// if (this.audioInfo.audioStatus == 'end') {
// this.saveRecord();
// }
// return;
// }
const result = await this.checkUploadFile(res.tempFilePath);
const isContinue = this.hasErrorFile();
if (isContinue) {
this.handleErrorFile(res.tempFilePath, UPLOAD_STATUS.fail);
return;
}
//模拟上传失败
const x = Math.random() * 10 > 5 ? "" : "x";
const result = await this.checkUploadFile(res.tempFilePath + x);
if (result instanceof Error) {
console.error("上传失败:", result);
const { customerName, phoneNumber, salesUuid, carModel, staffName } =
......@@ -220,11 +198,13 @@ export default {
this.$sendSentry(
`重试多次失败:手机号-${phoneNumber} 姓名-${customerName} 销售-${staffName} 车型-${carModel} 员工-${name},失败原因-${result}`
);
// this.handleErrorFile(res.tempFilePath, UPLOAD_STATUS.fail);
// return;
const saveResult = await uni.saveFile({
tempFilePath: res.tempFilePath,
}); // 保存文件到本地
this.handleErrorFile(saveResult[1].savedFilePath, UPLOAD_STATUS.fail);
return;
} else {
// this.handleErrorFile(result, UPLOAD_STATUS.success);
this.handleErrorFile(result, UPLOAD_STATUS.success);
}
const storageFile = [...this.audioInfo.audioList, result];
uni.$storage.set("storageFile", storageFile);
......@@ -237,16 +217,20 @@ export default {
},
/**保存记录*/
saveRecord() {
console.log("保存记录");
const recordUrlList = JSON.parse(uni.$storage.get("errorFile") || "[]");
let recordList = JSON.parse(uni.$storage.get("recordList") || "[]");
recordList = [
...recordList,
{
...this.getParams(),
recordUrlList,
},
...recordList,
];
uni.$storage.set("recordList", JSON.stringify(recordList));
uni.hideLoading();
uni.$storage.set("errorFile", "");
console.log(recordList, "recordList");
},
/**是否存在错误文件*/
hasErrorFile() {
......@@ -261,42 +245,36 @@ export default {
const errorFileList = JSON.parse(uni.$storage.get("errorFile") || "[]");
const errorFile = [...errorFileList, { file, status }];
uni.$storage.set("errorFile", JSON.stringify(errorFile));
},
/**上传记录*/
async handleRerord(val) {
let recordList = JSON.parse(uni.$storage.get("recordList") || "[]");
let idx = recordList.findIndex(
(item) => item.receptionStartTime == val.receptionStartTime
);
let recordUrlList = val.recordUrlList;
// 上传失败的记录
for (let i of recordUrlList) {
if (i.status == UPLOAD_STATUS.fail) {
const result = await this.checkUploadFile(i.file);
if (!(result instanceof Error)) {
i.status = UPLOAD_STATUS.success;
console.log(this.audioInfo.audioStatus, errorFile, "errorFile");
if (
this.audioInfo.audioStatus == "end" &&
errorFile.find((i) => i.status == UPLOAD_STATUS.fail)
) {
this.saveRecord();
}
}
}
// 判断是否全部上传成功
if (recordUrlList.every((i) => i.status == UPLOAD_STATUS.success)) {
recordList.splice(idx, 1);
val.recordUrlList = val.recordUrlList.map((i) => i.file);
this.uploadVoice(val);
uni.$storage.set("recordList", JSON.stringify(recordList));
if (
this.audioInfo.audioStatus == "end" &&
errorFile.every((i) => i.status == UPLOAD_STATUS.success)
) {
uni.$storage.set("errorFile", "");
}
},
async checkUploadFile(tempFilePath) {
console.log(tempFilePath);
let attempt = 0;
let errorMsg = "";
while (attempt < 5) {
while (attempt < 2) {
try {
const result = await upload(tempFilePath);
// 上传成功
return result;
} catch (error) {
if (attempt == 0) {
this.$sendSentry(`第一次上传失败:文件${tempFilePath}`);
const { customerName, phoneNumber } =
this.$store.state.user.customerInfo;
this.$sendSentry(
`第一次上传失败:姓名-${customerName},手机号-${phoneNumber},文件${tempFilePath}`
);
}
errorMsg = error;
attempt++;
......@@ -328,16 +306,10 @@ export default {
let finish_timer = null;
this.setAudioInfo({ audioStatus: "end" });
//直接退出
if (!status) {
uni.showLoading({
mask: true,
title: "处理中请稍后...",
title: status ? "" : "处理中请稍后...",
});
// setTimeout(() => {
// uni.hideLoading();
// clearInterval(finish_timer);
// }, 1000 * 60);
}
this.times = 0;
clearInterval(this.timer);
this.timer = null;
......@@ -352,7 +324,7 @@ export default {
clearInterval(finish_timer);
}
}, 300);
}, 1500),
}, 500),
//监听点击事件
initTime() {
if (this.audioInfo.audioStatus != "start") return;
......
/*
* @Author: 前端 qianduan01@didihu.com.cn
* @Date: 2024-04-08 11:28:48
* @LastEditors: 前端 qianduan01@didihu.com.cn
* @LastEditTime: 2024-04-26 10:04:31
* @FilePath: \gl_tape\mixin\click.js
* @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
*/
const UPLOAD_STATUS = {
// 上传状态
success: 1,
fail: 2,
};
import upload from "@/utils/ossUploadFile/uploadFile.js";
import utils from "@/utils/utils.js";
export default {
mounted() {
// this.checkRecord();
// setInterval(() => {
// this.checkRecord();
// }, 1000 * 60 * 10);
},
methods: {
checkRecord() {
utils.isNetWork().then(async (res) => {
let recordList = JSON.parse(uni.$storage.get("recordList") || "[]");
console.log(recordList, "recordList");
for (let i = 0; i < recordList.length; i++) {
await this.handleRerord(recordList[i]);
}
});
},
/**上传记录*/
async handleRerord(val) {
let recordList = JSON.parse(uni.$storage.get("recordList") || "[]");
let idx = recordList.findIndex(
(item) => item.receptionStartTime == val.receptionStartTime
);
let recordUrlList = val.recordUrlList;
// 上传失败的记录
for (let i of recordUrlList) {
if (i.status == UPLOAD_STATUS.fail) {
const filePath = i.file;
console.log(filePath, "filePath");
const result = await this.checkFileUpload(filePath);
if (!(result instanceof Error)) {
i.status = UPLOAD_STATUS.success;
i.file = result;
}
}
}
// 判断是否全部上传成功
if (recordUrlList.every((i) => i.status == UPLOAD_STATUS.success)) {
val.recordUrlList = val.recordUrlList.map((i) => i.file);
try {
const res = await uni.$api.commonApi.saveRecCustomer(val);
console.log(res, val);
recordList.splice(idx, 1);
uni.$storage.set("recordList", JSON.stringify(recordList));
} catch (err) {
Promise.reject(error);
}
}
},
async checkFileUpload(tempFilePath) {
console.log(tempFilePath);
let attempt = 0;
let errorMsg = "";
while (attempt < 2) {
try {
const result = await upload(tempFilePath);
// 上传成功
return result;
} catch (error) {
errorMsg = error;
attempt++;
// 等待一段时间后重试
await new Promise((resolve) => setTimeout(resolve, 3000)); // 3秒后重试
}
}
// 达到最大尝试次数后,如果上传仍然失败,可以进行相应的处理
console.error("上传失败,达到最大尝试次数");
// 返回一个错误或者进行其他操作
return new Error(errorMsg);
},
},
};
<template>
<scroll-view
class="record-box"
scroll-y
@scrolltolower="pageonReachBottom"
@scroll="scroll"
>
<view class="record-box">
<view class="record-content">
<view class="data-box">
<template v-for="(i, index) in dataList">
......@@ -31,7 +26,33 @@
</view>
</template>
</view>
<view :class="['data-tabs-box', { sticky: sticky }]">
<view class="data-container">
<view :class="['type-box']">
<view
class="tab-item"
v-for="(i, index) in typeList"
:key="index"
@click="changeType(index, 'firstIndex')"
>
<view
class="sprite-icon"
:class="[
firstIndex == index ? `icon-${firstClass[index]} active` : '',
]"
:style="{ left: firstLeft[index] }"
></view>
<view class="text" :class="[firstIndex == index ? `active` : '']"
>{{ i.tabName
}}{{
i.num && recordFailList.length > 0
? `(${recordFailList.length})`
: ""
}}</view
>
</view>
</view>
<view class="tabs-bottom"></view>
<view v-if="firstIndex == 0" class="data-tabs-box">
<view class="data-tabs">
<template v-for="(i, index) in dateList">
<view
......@@ -44,6 +65,16 @@
<view :class="['active-btn', `active-btn-${dateIndex}`]"></view>
</view>
</view>
<scroll-view
class="record-list"
:style="{
height:
firstIndex == 0 ? 'calc(100% - 300rpx)' : 'calc(100% - 180rpx)',
}"
scroll-y
@scrolltolower="pageonReachBottom"
@scroll="scroll"
>
<view class="list">
<template v-if="flag">
<template v-if="list.length && list[0] && list[0].length">
......@@ -90,9 +121,11 @@
<template v-if="nothing">
<view class="end-text">到底了!</view>
</template>
</scroll-view>
</view>
<view class="bottom-mask"></view>
</scroll-view>
</view>
</view>
</template>
<script type="text/ecmascript-6">
......@@ -100,7 +133,7 @@ import dayjs from 'dayjs'
const dayImgUrl = require('@/assets/images/common/day.webp')
const weekImgUrl = require('@/assets/images/common/week.webp')
const monthImgUrl = require('@/assets/images/common/month.webp')
import utils from "@/utils/utils.js";
export default {
name: '',
data () {
......@@ -126,6 +159,13 @@ export default {
icon: monthImgUrl
}
],
typeList: [
{ tabName: '已上传' },
{ tabName: '待上传',num:true },
],
firstIndex: 0,
firstLeft: ['0rpx', '352rpx', '756rpx'],
firstClass: ['first-nav', 'second-nav', 'second-nav'],
dateList: [
{ text: '今日' },
{ text: '本周' },
......@@ -138,6 +178,7 @@ export default {
{ label: '开始接待', key: 'startTime' },
{ label: '结束接待', key: 'endTime' },
],
recordFailList:[],
dateIndex: 0,
pageNum: 1,
total: 0,
......@@ -150,11 +191,54 @@ export default {
},
mounted () {
this.init()
this.getRecordNum()
},
methods: {
changeType (index, name) {
if (this[name] == index) return // 点击同一个
this.direction = ''
console.log(index, name, this[name])
if (this[name] < index) {
this.direction = 'right'
} else {
this.direction = 'left'
}
this[name] = index
this.list=[]
this.pageNum = 1;
if(index == 0) {
this.changeIndex(this.dateIndex,true)
}else {
this.getRecordFail()
}
},
scroll (e) {
this.sticky = e.detail.scrollTop >= 148
},
getRecordNum() {
let recordFailListAll = JSON.parse(uni.$storage.get("recordList") || "[]");
const { shopMerchantId,sceneType } = uni.$storage.get("userInfo");
let recordFailList = recordFailListAll.filter(i=>{
console.log(i.bussinessType,sceneType)
return i.merchantId == shopMerchantId && i.bussinessType == (sceneType == 0 ? 1 : 2)
})
this.recordFailList = recordFailList
},
getRecordFail() {
this.getRecordNum()
this.list[0] = this.recordFailList.map(i=>{
return {
receptionStatus:i.receptionStatus,
phoneNumber:i.phoneNumber,
salesName:i.salesName,
customerName:i.customerName,
carModel:i.carModel,
duration:this.formatSeconds(new Date(i.receptionEndTime).getTime() - new Date(i.receptionStartTime).getTime()),
startTime: i.receptionStartTime.replace(/\//g,'.'),
endTime: i.receptionEndTime.replace(/\//g,'.')
}
})
},
init () {
this.dateList.map((e, index) => {
const tatget = ['day', 'week', 'month'][index]
......@@ -194,7 +278,9 @@ export default {
},
async getReceptionList () {
try {
uni.showLoading()
uni.showLoading({
mask: true
})
const { dateList, dateIndex, pageNum, pageSize } = this,
{ startTime, endTime } = dateList[dateIndex],
userInfo = uni.$storage.get("userInfo"),
......@@ -215,7 +301,9 @@ export default {
e.endTime = dayjs(e.receptionEndTime).format("YYYY.MM.DD HH:mm:ss")
e.phoneNumber = phoneNumber.slice(0, 3) + " " + phoneNumber.slice(3, 7) + " " + phoneNumber.slice(7)
})
this.list[pageNum - 1] = list
this.$set(this.list,pageNum - 1,list)
// this.list[pageNum - 1] = list
console.log(this.list)
this.flag = true
this.total = total
} catch (error) {
......@@ -245,8 +333,8 @@ export default {
return formattedTime
}
},
changeIndex (index) {
if (this.dateIndex == index) return
changeIndex (index,isType = false) {
if (this.dateIndex == index && !isType) return
this.flag = false
this.nothing = false
this.total = 0
......@@ -258,6 +346,7 @@ export default {
},
pageonReachBottom () {
let { pageNum, total, nothing, pageSize } = this
console.log(pageNum, total, nothing, pageSize)
if (!nothing) nothing = 'nothing'
if (Math.ceil(total / pageSize) > pageNum) {
this.pageNum += 1
......@@ -301,19 +390,71 @@ export default {
height: 100%;
.record-content {
padding: 96rpx 0;
.data-container {
background: #ffffff;
border-radius: 48rpx;
margin-top: 48rpx;
height: calc(100vh - 440rpx);
.type-box {
position: relative;
display: flex;
width: 100%;
background-color: #eef4fe;
height: 176rpx;
line-height: 128rpx;
border-radius: 48rpx 48rpx 0 0;
z-index: 0;
.tab-item {
width: 400rpx;
text-align: center;
font-weight: 500;
font-size: 40rpx;
color: #1f2133;
.text {
position: relative;
text-align: center;
width: 400rpx;
}
.active {
position: absolute;
top: 0;
z-index: -1;
font-weight: 700;
font-size: 40rpx;
color: #2c66f7;
&::after {
content: "";
position: absolute;
bottom: 0;
left: 50%;
transform: translateX(-50%);
width: 48rpx;
height: 8rpx;
background-color: #2c66f7;
border-radius: 16rpx;
}
}
}
}
}
}
.record-list {
height: calc(100% - 380rpx);
margin-top: 24rpx;
}
.list {
display: flex;
flex-wrap: wrap;
gap: 48rpx 60rpx;
padding-top: 48rpx;
padding: 0rpx 64rpx 20rpx;
.item {
width: 640rpx;
width: 608rpx;
background: #ffffff;
border-radius: 16rpx;
box-sizing: border-box;
padding: 24rpx 32rpx;
position: relative;
box-shadow: 0 8rpx 24rpx 0 #2c66f71a;
border-radius: 16rpx;
.status {
position: absolute;
top: 24rpx;
......@@ -452,61 +593,64 @@ export default {
}
}
}
.tabs-bottom {
margin-top: -45rpx;
background: #fff;
height: 45rpx;
position: relative;
z-index: 3;
}
.data-tabs-box {
position: relative;
top: 0;
z-index: 3;
width: calc(100% + 120rpx);
transform: translateX(-60rpx);
padding-top: 80rpx;
.data-tabs {
display: flex;
justify-content: space-between;
width: 784rpx;
height: 70rpx;
border-radius: 370rpx;
margin: 0 auto;
width: 552rpx;
height: 76rpx;
background-color: #f2f2f2;
border-radius: 16rpx;
margin-left: 60rpx;
position: relative;
&::after {
position: absolute;
z-index: -2;
background: #ffffffb3;
background: #ffffff;
width: 100%;
height: 100%;
border-radius: 370rpx;
left: 0;
top: 0;
content: "";
}
.tab {
width: 240rpx;
height: 70rpx;
width: 184rpx;
height: 76rpx;
justify-content: center;
font-weight: 500;
font-size: 32rpx;
color: #333333;
color: #1f2133;
z-index: 10;
}
.active {
color: #ffffff;
}
.active-btn {
position: absolute;
width: 240rpx;
height: 70rpx;
background: #3b73ff;
border-radius: 360rpx;
top: 0;
z-index: -1;
width: 180rpx;
height: 68rpx;
background: #ffffff;
top: 4rpx;
transition: all 0.15s;
border-radius: 16rpx;
}
.active-btn-0 {
left: 0;
left: 4rpx;
}
.active-btn-1 {
left: 272rpx;
left: 184rpx;
}
.active-btn-2 {
left: 544rpx;
left: 368rpx;
}
}
}
......
......@@ -845,4 +845,9 @@ export default {
background-position-x: -100%;
}
}
.webview-container {
width: 100rpx;
height: 100rpx;
opacity: 0;
}
</style>
......@@ -16,6 +16,8 @@ export const STORAGE_OBJECTkEY = {
noSignInUuid: "noSignInUuid",
noviceGuideStatus: "noviceGuideStatus",
accountLength: "accountLength",
errorFile: "errorFile",
recordList: "recordList",
};
// export const IMG_VERSION = async () => {
......
class FileManager {
writeFile(addr, data) {
plus.io.requestFileSystem(
plus.io.PUBLIC_DOCUMENTS, // 程序公用文档目录常量
(fs) => {
// 创建或打开文件, fs.root是根目录操作对象,直接fs表示当前操作对象
fs.root.getFile(
addr,
{
create: true, // 文件不存在则创建
},
(fileEntry) => {
// 文件在手机中的路径
console.log(fileEntry.fullPath);
fileEntry.createWriter((writer) => {
// 写入文件成功完成的回调函数
writer.onwrite = (e) => {
console.log("写入成功");
};
// 向文件中写入数据
writer.write(JSON.stringify(data));
});
},
(e) => {
console.log("getFile failed: " + e.message);
}
);
},
(e) => {
console.log(e.message);
}
);
}
readFile(addr) {
let that = this;
return new Promise((resolve, reject) => {
plus.io.requestFileSystem(
plus.io.PUBLIC_DOCUMENTS,
(fs) => {
fs.root.getFile(
addr,
{
create: true,
},
(fileEntry) => {
fileEntry.file(function (file) {
console.log("文件大小:" + file.size + "-- 文件名:" + file.name);
//创建读取文件对象
let fileReader = new plus.io.FileReader();
//以文本格式读取文件数据内容
fileReader.readAsText(file, "utf-8");
//文件读取操作完成时的回调函数
fileReader.onloadend = function (evt) {
resolve(evt.target.result);
//console.log("提取的服务器地址:", sURL);
};
});
},
(e) => {
reject(e);
console.log(e);
}
);
},
(e) => {
reject(e);
console.log(e.message);
}
);
});
}
}
export default new FileManager();
......@@ -35,10 +35,10 @@ const uploadFile = function (filePath) {
const aliyunServerURL = config.uploadUrl; // OSS地址
const accessid = config.OSSAccessKeyId;
const policyBase64 = getPolicyBase64();
try {
const { signature, securityToken, lsaccessKeyId } = await getSignature(
policyBase64
); // 获取签名
uni.uploadFile({
url: aliyunServerURL, // 开发者服务器url
filePath: filePath, // 要上传文件资源的路径
......@@ -83,6 +83,9 @@ const uploadFile = function (filePath) {
reject(err);
},
});
} catch {
reject("获取签名失败");
}
});
};
......@@ -103,8 +106,10 @@ const getPolicyBase64 = function () {
// 生成签名
const getSignature = function (policyBase64) {
return new Promise(async (reslove) => {
const result = uni.$api.commonApi.getToken({}).then((res) => {
return new Promise(async (reslove, reject) => {
const result = uni.$api.commonApi
.getToken({})
.then((res) => {
const { lsaccessKeySecret, securityToken, lsaccessKeyId } = res;
const bytes = Crypto.HmacSHA1(policyBase64, lsaccessKeySecret);
const signature = Crypto.enc.Base64.stringify(bytes);
......@@ -113,6 +118,9 @@ const getSignature = function (policyBase64) {
securityToken,
lsaccessKeyId,
});
})
.catch((error) => {
reject(error);
});
// const result = await uni.request({
// url: 'https://dj.test.glsx.com.cn/rop-dj-smartcarlife/router',
......
......@@ -76,10 +76,25 @@ var throttle = function (fn, delay) {
}, delay);
};
};
//检查是否有网络
var isNetWork = function () {
return new Promise((resolve, reject) => {
uni.getNetworkType({
complete: function (res) {
if (res.networkType == "none") {
reject();
} else {
resolve();
}
},
});
});
};
export default {
convertDateTimeFormat,
deepClone,
accDiv,
debounce,
throttle,
isNetWork,
};
Markdown is supported
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!