投诉建议页面上传问题修改(index路由改为evaluate)

This commit is contained in:
zzyuan 2025-09-02 10:07:30 +08:00
parent a44594df00
commit d24ca009ce
12 changed files with 827 additions and 388 deletions

View File

@ -277,7 +277,7 @@
}
},
{
"path": "pages/feedback/index",
"path": "pages/feedback/evaluate",
"style": {
"navigationBarTitleText": "投诉建议"
}

View File

@ -98,7 +98,8 @@ export default {
currentTab: 0,
content: '',
fileList: [],
contactInfo: ''
contactInfo: '',
description:""
}
},
onLoad() {
@ -206,11 +207,11 @@ export default {
"uploadKey":'system',
"base64File":base64
}
uploadBase64(param).then(res => {
uploadBase64(param).then(res => {
if(res.code==200){
resolve(res.data)
}
})
})
})
});
},
@ -297,6 +298,7 @@ export default {
.upload-box {
margin-top: 30rpx;
margin-left: 10px;
display: flex;
.upload-btn {

View File

@ -1,372 +0,0 @@
<template>
<page-meta :page-font-size="fontValue+'px'" :root-font-size="fontValue+'px'"></page-meta>
<view class="feedback-page">
<view class="content-box">
<view class="border-box">
<view style="font-size: 32rpx;margin-bottom: 5px;"><span style="color: red;">*</span>食堂 </view>
<view @click="showCarteen=true" style="width: 100%;height: auto;">
<view style="border: 1px solid #dadbde;padding: 12rpx;height: 30px;">
{{canteenName}}
</view>
</view>
<u-action-sheet
:show="showCarteen"
:actions="actions"
title="请选择食堂"
@close="showCarteen=false"
@select="carteenSelect"
></u-action-sheet>
</view>
<view class="border-box">
<view style="font-size: 32rpx;margin-bottom: 5px;"><span style="color: red;">*</span>投诉建议 </view>
<u--textarea
v-model="content"
placeholder="请详细补充您的问题或建议"
:maxlength="300"
height="200"
count
>
<text slot="count" class="word-count">{{ content.length }}/300</text>
</u--textarea>
</view>
<!-- 图片上传 -->
<view class="upload-box">
<view style="font-size: 32rpx;margin-bottom: 5px;">图片(选填) </view>
<u-upload
:fileList="fileList"
@afterRead="afterRead"
@delete="deletePic"
:maxCount="5"
multiple
>
<view class="upload-btn">
<u-icon name="camera" size="44" color="#666666"></u-icon>
<text class="upload-text">添加图片</text>
</view>
</u-upload>
</view>
<!-- 联系方式 -->
<view class="contact-box">
<text class="contact-title">请留下您的联系方式</text>
<u--input
v-model="contactInfo"
placeholder="电话号码/电子邮箱(仅工作人员可见)"
border="bottom" maxlength="11"
></u--input>
</view>
</view>
<!-- 提交按钮 -->
<view class="submit-btn">
<u-button
shape="squrd"
@click="submitFeedback"
style="margin-bottom: 10px;font-size: 28rpx;"
:customStyle="{
width: '100%',
height: '88rpx',
background: '#ff6633',
color: '#ffffff',
border: 'none'
}"
>提交</u-button>
<u-button
shape="squrd"
@click="goHistory"
:customStyle="{
width: '100%',
height: '88rpx',
background: '#fff',
color: '#000',
border: '1px solid #000'
}" style="font-size: 28rpx;"
>历史记录</u-button>
</view>
</view>
</view>
</template>
<script>
import { getAllCanteenStallApi,postCanteenPlaintApi } from "@/api/mine/index.js"
import { pathToBase64, base64ToPath } from 'image-tools';
import { uploadBase64 } from "@/api/upload"
export default {
data() {
return {
fontValue:uni.getStorageSync('fontSize') || 8,
carteenName:"",
showCarteen:false,
actions:[],
canteenId:"",
canteenName:"",
currentTab: 0,
content: '',
fileList: [],
contactInfo: ''
}
},
onLoad() {
this.getAllCanteenStall()
},
methods: {
//
async getAllCanteenStall() {
const res = await getAllCanteenStallApi({})
let arr=[]
if(res.length>0){
res.forEach(item=>{
let obj={
id:item.canteenId,
name:item.canteenName
}
arr.push(obj)
})
}
this.actions = arr
},
carteenSelect(e){
console.log(e)
this.canteenId = e.id
this.canteenName = e.name
},
//
async submitFeedback() {
console.log(this.fileList)
if(this.canteenId==""){
uni.$u.toast('请选择食堂')
return
}
if(this.content==""){
uni.$u.toast('请认真填写建议')
return
}
let arr = []
this.fileList.forEach(item=>{
arr.push(item.url)
})
let param = {
"canteenId": this.canteenId,
"canteenName": this.canteenName,
"complaintPictureList": arr,
"content": this.content,
"mobile": this.contactInfo,
// "starLevel": 6,
"custId": uni.getStorageSync('custId')
}
console.log(param)
const res = await postCanteenPlaintApi(param)
if(res.code==200){
uni.showToast({
title: '提交成功',
icon: 'none'
});
setTimeout(()=>{
uni.navigateBack()
},800)
}
},
//
goHistory(){
uni.navigateTo({
url: `/pages/feedback/history`
})
},
//
async afterRead(event) {
// console.log(event)
// multiple true , file
let lists = [].concat(event.file);
let fileListLen = this[`fileList${event.name}`].length;
lists.map((item) => {
this[`fileList${event.name}`].push({
...item,
status: "uploading",
message: "上传中",
});
});
console.log(lists)
for (let i = 0; i < lists.length; i++) {
const result = await this.uploadFilePromise(lists[i].url);
console.log(result)
let item = this[`fileList${event.name}`][fileListLen];
this[`fileList${event.name}`].splice(
fileListLen,
1,
Object.assign(item, {
status: "success",
message: "",
url: result.fileNameUrl,
})
);
fileListLen++;
}
},
//
uploadFilePromise(url) {
return new Promise((resolve, reject) => {
this.imgToBase64(url).then(base64 => {
let param = {
"MERCHANT-ID":"378915229716713472",
"uploadKey":'system',
"base64File":base64
}
uploadBase64(param).then(res => {
if(res.code==200){
resolve(res.data)
}
})
})
});
},
imgToBase64(data) {
return new Promise((resolve, reject) => {
pathToBase64(data).then(base64 => {
resolve(base64)
}).catch(error => {
console.error(error)
reject(error)
})
})
},
deletePic(event) {
this.fileList.splice(event.index, 1);
},
}
}
</script>
<style lang="scss" scoped>
/deep/.u-action-sheet__item-wrap {
overflow: auto;
max-height: 50vh;
}
.feedback-page {
height:96vh;
overflow-y: auto;
background-color: #FFF;
.type-section {
background-color: #ffffff;
padding: 30rpx 30rpx 20rpx;
.section-title {
font-size: 28rpx;
color: #333333;
margin-bottom: 20rpx;
font-weight: 550;
display: block;
}
}
.tab-box {
display: flex;
.tab-item {
flex: 1;
text-align: center;
font-size: 28rpx;
color: #666666;
padding: 16rpx 0;
position: relative;
border: 1px solid rgba(15,39,75,0.4);;
margin-right: 20rpx;
border-radius: 2px;
&.active {
color: #333333;
background-color: #fff2ef;
border: 1px solid #FF6816;
}
}
}
.content-box {
margin-top: 20rpx;
padding: 20rpx;
.border-box{
background-color: #ffffff;
padding: 16rpx;
border-radius: 8px;
}
.word-count {
position: absolute;
right: 20rpx;
bottom: 20rpx;
font-size: 24rpx;
color: #999999;
}
}
.upload-box {
margin-top: 30rpx;
.upload-btn {
width: 160rpx;
height: 160rpx;
background-color: #f7f8fa;
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
border-radius: 8rpx;
.upload-text {
font-size: 24rpx;
color: #666666;
margin-top: 10rpx;
}
}
}
.contact-box {
margin-top: 40rpx;
background-color: #ffffff;
padding: 20rpx 16rpx 16rpx 16rpx;
border-radius: 8px;
.contact-title {
font-size: 28rpx;
color: #333333;
margin-bottom: 20rpx;
}
}
.submit-btn {
padding: 20rpx 30rpx;
margin-top: 20px;
}
}
::v-deep .u-textarea {
padding: 20rpx;
background-color: #f7f8fa;
border-radius: 8rpx;
}
::v-deep .u-input {
&__content {
&__field-wrapper {
&__field {
font-size: 28rpx;
}
}
}
}
::v-deep .u-upload {
&__wrap {
display: flex;
flex-wrap: wrap;
gap: 20rpx;
}
}
.u-textarea {
background-color: #ffffff;
}
.upload-btn {
background-color: #ffffff !important;
border: 1px solid #dadbde;
}
</style>

View File

@ -88,7 +88,7 @@ export default {
}
},
onShow() {
uni.reLaunch({ url: '/pages/feedback/index' })
// uni.reLaunch({ url: '/pages/feedback/evaluate' })
// setTimeout(()=>{
if(Cookies.get('remember')){
this.remember = [Cookies.get('remember')] || [];

View File

@ -41,7 +41,7 @@
</view>
<!-- 投诉建议 -->
<view class="grid-item" @click="navigateTo('/pages/feedback/index')">
<view class="grid-item" @click="navigateTo('/pages/feedback/evaluate')">
<view class="icon-wrapper">
<image style="width: 120rpx;height: 120rpx;" src="/static/images/my/complaints.png"></image>
</view>

View File

@ -42,14 +42,16 @@
</template>
<script>
import { decryptWithSM4 } from '@/utils/sm'
export default {
data() {
return {
fontValue:uni.getStorageSync('fontSize') || 8,
currentPhone: uni.getStorageSync('mobile')
}
},
data() {
return {
fontValue:uni.getStorageSync('fontSize') || 8,
currentPhone: decryptWithSM4(uni.getStorageSync('mobile'))
}
},
onLoad() {
},
methods: {
goBack() {

View File

@ -0,0 +1,7 @@
## 1.0.22023-11-01
更换App端转换本地链接的方法
添加App端文件拓展名过滤
## 1.0.12023-09-04
优化部分逻辑
## 1.0.02023-09-03
支持图片、视频选择上传H5、微信小程序App支持文件选择上传

View File

@ -0,0 +1,285 @@
<!-- eslint-disable -->
<template>
<view>
<!-- #ifdef APP-PLUS -->
<view class="xe-upload" v-html="renderInput" :props="mergeProps" :change:props="XeUpload.renderProps"></view>
<!-- #endif -->
</view>
</template>
<script>
import {
chooseMedia,
chooseFile,
chooseMessageFile,
uploadFile,
} from '../../tools/apis';
import {
deepMerge,
awaitWrap,
base64ToPath,
isArray,
} from '../../tools/tools';
export default {
name: 'XeUpload',
props: {
options: {
default: () => ({}),
type: Object,
},
},
data() {
return {
id: 0, // APPID
renderInput: '', // APP
};
},
computed: {
mergeOptions({ options = {} }) {
const tmpOptions = {
name: 'file',
};
return deepMerge(tmpOptions, options);
},
mergeProps({ id, renderInput, mergeOptions }) {
return {
id,
renderInput,
upload: mergeOptions,
};
},
},
methods: {
//
async upload(type, config = {}) {
let tmpResult = [];
if (['image', 'video'].includes(type)) {
const [err, res] = await chooseMedia(type, config);
if (err) return this.handleError(err);
tmpResult = res?.tempFiles || [];
}
// H5 || APP-PLUS || MP-WEIXIN
if (['file'].includes(type)) {
let tmpFiles = {};
let tmpErr = null;
// #ifdef H5
[tmpErr, tmpFiles] = await chooseFile(config);
// #endif
// #ifdef MP-WEIXIN
[tmpErr, tmpFiles] = await chooseMessageFile(config);
// #endif
// #ifdef APP-PLUS
this.id = Math.floor(Math.random() * 100000000 + 1);
this.initInput(config.extension);
// #endif
if (tmpErr) return this.handleError(tmpErr);
tmpResult = tmpFiles?.tempFiles || [];
}
this.handleUpload(tmpResult);
},
//
initInput(extension) {
const { id } = this;
let accept = extension;
if (isArray(extension)) {
accept = extension.join(',');
}
this.renderInput = `<input type="file" id="xe-upload-${id}" name="xe-upload" ${accept ? 'accept="' + accept + '"' : ''} />`;
},
// url
async handleUpload(files = []) {
if (files.filter((e) => Boolean(e)).length === 0) return;
const { mergeOptions } = this;
if (!mergeOptions.url) {
return this.handleEmits({
type: 'choose',
data: files,
});
}
const tmpUploads = files.map((e) =>
uploadFile(
{
...mergeOptions,
filePath: e.tempFilePath,
},
e,
)
);
const [err, res] = await awaitWrap(Promise.all(tmpUploads));
if (err) return this.handleError(err);
this.handleEmits({
type: 'success',
data: res,
});
},
//
handleError(error) {
this.handleEmits({
type: 'warning',
data: error,
});
},
//
async handleEmits(e) {
// #ifdef APP-PLUS
if (e.type === 'choose') {
// base64
for (let i = 0; i < e.data.length; i += 1) {
const item = e.data[i];
if (!item.base64Url) {
continue;
}
const [parseError, parseUrl] = await awaitWrap(base64ToPath(item.base64Url, item.name));
if (!parseError) {
e.data[i].tempFilePath = parseUrl;
} else {
e.data[i].tempFilePath = item.base64Url;
}
delete e.data[i].base64Url;
}
}
// #endif
this.$emit('callback', e);
},
},
};
</script>
<!-- #ifdef APP-PLUS -->
<script module="XeUpload" lang="renderjs">
import {
appUploadFile,
} from '../../tools/apis';
import {
awaitWrap,
fileToBase64,
} from '../../tools/tools';
export default {
data() {
return {
id: 0, // ID
uploadOptions: {}, //
};
},
methods: {
// XeUpload renderjs
renderProps(info) {
const { id, renderInput, upload } = info;
if (!renderInput) return;
this.id = id;
this.uploadOptions = upload;
this.$nextTick(() => {
const dom = document.getElementById(`xe-upload-${id}`);
dom.addEventListener('change', () => {
this.handleUpload();
});
dom?.click?.();
});
},
// (url)
async handleUpload() {
const {
url,
name,
header = {},
formData = {},
} = this.uploadOptions || {};
const dom = document.getElementById(`xe-upload-${this.id}`);
if (!dom.files[0]) return;
const tmpFileList = Array.from(dom.files);
const tmpUploads = [];
for (let i = 0; i < tmpFileList.length; i += 1) {
const e = tmpFileList[i];
let tmpType = 'file';
if (e.type.includes('image')) {
tmpType = 'image';
}
if (e.type.includes('video')) {
tmpType = 'video';
}
const tmpExts = {
size: e.size,
name: e.name,
type: e.type,
fileType: tmpType,
tempFilePath: '',
base64Url: '',
};
// url
if (!url) {
const [parseError, parseUrl] = await awaitWrap(fileToBase64(dom.files[i]));
if (!parseError) {
tmpExts.base64Url = parseUrl;
}
tmpUploads.push(tmpExts);
continue;
};
const tmpData = new FormData();
tmpData.append(name, dom.files[i], e.name);
for (let key in formData) {
tmpData.append(key, formData[key]);
}
//
const onprogress = (ev) => {
if(ev.lengthComputable) {
var result = (ev.loaded / ev.total) * 100;
this.handleRenderEmits({
type: 'onprogress',
data: {
progress: Math.floor(result),
current: i + 1,
total: tmpFileList.length,
},
});
};
}
tmpUploads.push(appUploadFile({
url,
header,
formData: tmpData
}, tmpExts, onprogress ));
}
// url
if (!url) {
return this.handleRenderEmits({
type: 'choose',
data: tmpUploads,
});
}
this.handleRenderEmits({
type: 'onprogress',
data: {
progress: 0,
current: 1,
total: tmpFileList.length,
},
});
//
const [err, res] = await awaitWrap(Promise.all(tmpUploads));
if (err) {
return this.handleRenderEmits({
type: 'warning',
data: err,
});
}
this.handleRenderEmits({
type: 'success',
data: res,
});
},
// XeUpload
handleRenderEmits(data) {
this.$ownerInstance.callMethod('handleEmits', data);
},
},
};
</script>
<!-- #endif -->
<style scoped>
.xe-upload {
display: none;
}
</style>

View File

@ -0,0 +1,80 @@
{
"id": "xe-upload",
"displayName": "文件选择、文件上传组件(图片,视频,文件等)",
"version": "1.0.2",
"description": "H5、微信小程序、App端支持图片视频文件选择上传其他端暂不支持文件选择上传",
"keywords": [
"App、H5、微信小程序、图片视频文件上传"
],
"repository": "",
"engines": {
},
"dcloudext": {
"type": "component-vue",
"sale": {
"regular": {
"price": "0.00"
},
"sourcecode": {
"price": "0.00"
}
},
"contact": {
"qq": ""
},
"declaration": {
"ads": "无",
"data": "无",
"permissions": "无"
},
"npmurl": ""
},
"uni_modules": {
"dependencies": [],
"encrypt": [],
"platforms": {
"cloud": {
"tcb": "y",
"aliyun": "y"
},
"client": {
"Vue": {
"vue2": "y",
"vue3": "u"
},
"App": {
"app-vue": "y",
"app-nvue": "u"
},
"H5-mobile": {
"Safari": "y",
"Android Browser": "y",
"微信浏览器(Android)": "y",
"QQ浏览器(Android)": "y"
},
"H5-pc": {
"Chrome": "y",
"IE": "u",
"Edge": "y",
"Firefox": "y",
"Safari": "y"
},
"小程序": {
"微信": "y",
"阿里": "y",
"百度": "y",
"字节跳动": "y",
"QQ": "y",
"钉钉": "y",
"快手": "y",
"飞书": "y",
"京东": "y"
},
"快应用": {
"华为": "y",
"联盟": "y"
}
}
}
}
}

View File

@ -0,0 +1,78 @@
# xe-upload
## 说明
不占用页面位置的上传组件;
H5、APP、微信小程序中可上传图片视频和文件其他端暂时只能上传图片和视频
> 上传图片通过[chooseMedia](https://uniapp.dcloud.net.cn/api/media/video.html#choosemedia)及[chooseImage](https://uniapp.dcloud.net.cn/api/media/image.html#chooseimage)实现
> 上传视频通过[chooseMedia](https://uniapp.dcloud.net.cn/api/media/video.html#choosemedia)及[chooseVideo](https://uniapp.dcloud.net.cn/api/media/video.html#choosevideo)实现
> H5端上传文件通过[chooseFile](https://uniapp.dcloud.net.cn/api/media/file.html#wx-choosemessagefile)实现
> APP上传文件通过[renderjs](https://uniapp.dcloud.net.cn/tutorial/renderjs.html#renderjs)实现
> 微信小程序上传文件通过[chooseMessageFile](https://developers.weixin.qq.com/miniprogram/dev/api/media/image/wx.chooseMessageFile.html)实现
## 使用
Attributes
| 参数 | 说明 | 类型 | 默认值 |
| ----------- | ----------- | ----------- | ----------- |
| options | 请求配置(参数与uni.uploadFile的参数一致) | object | { name: 'file' } |
Events
| 事件名 | 说明 | 参数 |
| ----------- | ----------- | ----------- |
| callback | 接收数据 | { type, data } |
callback type
| 参数 | 说明 |
| ----------- | ----------- |
| warning | 提示信息下文称warning回调 |
| success | 上传成功下文称success回调 |
| choose | 选择文件下文称choose回调 |
callback data
```
'callback.type === success' : [
{
"size": 176579, // 选择的文件的大小
"name": "Kafka.pdf", // 选择的文件的名称(小程序端可能会没有)
"type": "application/pdf",
"tempFilePath": "blob:http://192.168.137.1:8080/2585769b-3195-4f3d-b9f8-d9e99f55deec", // 临时路路径
"fileType": "file", // 文件类型[image, video, file]
"response": {
"result": {
"fileName": "Kafka.pdf",
"filePath": `http://localhost:3000/upload/e51d814b649122fc64892d0bc6383d07.pdf`,
},
"success": true,
}, // 上传返回的信息
}
]
'callback.type === choose' : [
{
"size": 176579, // 选择的文件的大小
"name": "Kafka.pdf", // 选择的文件的名称(小程序端可能会没有)
"type": "application/pdf",
"tempFilePath": "blob:http://192.168.137.1:8080/4204e460-f185-4fc9-9f4d-1bc50ab06981", // 文件临时路径
"fileType": "file", // 文件类型[image, video, file]
}
]
```
## 注意事项
#### 1、options入参中如果url为空则choose回调的data列表中只有选择文件能得到的信息和临时路径临时路径可用于自定义上传方法APP除外传入url选择文件后会自动上传到服务器此时choose回调不会触发而是执行success回调success回调的data列表会包括选择文件能得到的信息
#### 2、APP端文件建议直接上传到服务器拿到文件上传后的地址再进行其他操作(目前测试APP端file转换后的Blob Url无法用于uni.uploadFile所以建议APP文件直接上传)
#### 3、APP端文件暂时支持单个上传
#### 4、当uni.chooseMedia可用时会优先使用uni.chooseMedia
#### 5、具体使用可下载示例项目运行查看完整示例

View File

@ -0,0 +1,177 @@
// eslint-disable
import { awaitWrap } from './tools';
/**
* 从本地相册选择图片或使用相机拍照
* @param {object} config 参数详情 => https://uniapp.dcloud.net.cn/api/media/image.html#chooseimage
* @returns
*/
export const chooseImage = (config) => {
return awaitWrap(
new Promise((r, j) => {
uni.chooseImage({
...config,
success: (res) => {
const tmpFiles = res?.tempFiles.map((e) => ({
tempFilePath: e.path,
tempFile: e,
size: e.size,
name: e.name,
type: e.type,
fileType: 'image',
}));
return r({ type: 'image', ...res, tempFiles: tmpFiles });
},
fail: (err) => j({ mode: 'chooseImage', data: err }),
});
})
);
};
/**
* 拍摄视频或从手机相册中选视频返回视频的临时文件路径
* @param {object} config 参数详情 => https://uniapp.dcloud.net.cn/api/media/video.html#choosevideo
* @returns
*/
export const chooseVideo = (config) => {
return awaitWrap(
new Promise((r, j) => {
uni.chooseVideo({
...config,
success: (res) => {
const tmpFiles = [{
...res,
tempFilePath: res.tempFilePath,
tempFile: res.tempFile ?? {},
size: res.size,
name: res.name,
type: res.tempFile?.type,
fileType: 'video',
}];
return r({ type: 'video', tempFiles: tmpFiles });
},
fail: (err) => j({ mode: 'chooseVideo', data: err }),
});
})
);
};
/**
* 拍摄或从手机相册中选择图片或视频
* @param {object} config 参数详情 => https://uniapp.dcloud.net.cn/api/media/video.html#choosemedia
* @returns
*/
export const chooseMedia = (type, config) => {
if (!type) return console.error('chooseMedia type cannot be empty');
if (!uni.chooseMedia && type === 'image') return chooseImage(config);
if (!uni.chooseMedia && type === 'video') return chooseVideo(config);
return awaitWrap(
new Promise((r, j) => {
uni.chooseMedia({
...config,
mediaType: [type],
success: (res) => r(res),
fail: (err) => j({ mode: 'chooseMedia', data: err }),
});
})
);
};
/**
* 从本地选择文件(h5)
* @param {object} config 参数详情 => https://uniapp.dcloud.net.cn/api/media/file.html#wx-choosemessagefile
* @returns
*/
export const chooseFile = (config) => {
return awaitWrap(
new Promise((r, j) => {
uni.chooseFile({
...config,
success: (res) => {
const tmpFiles = res?.tempFiles.map((e) => {
let tmpType = 'file';
if (e.type.includes('image')) {
tmpType = 'image';
}
if (e.type.includes('video')) {
tmpType = 'video';
}
return {
tempFilePath: e.path,
tempFile: e,
size: e.size,
name: e.name,
type: e.type,
fileType: tmpType,
};
});
return r({ type: 'file', ...res, tempFiles: tmpFiles });
},
fail: (err) => j({ mode: 'chooseFile', data: err }),
});
})
);
};
/**
* 从本地选择文件(微信小程序)
* @param {object} config 参数详情 => https://developers.weixin.qq.com/miniprogram/dev/api/media/image/wx.chooseMessageFile.html
* @returns
*/
export const chooseMessageFile = (config) => {
return awaitWrap(
new Promise((r, j) => {
wx.chooseMessageFile({
...config,
success: (res) => {
const tmpFiles = res?.tempFiles.map((e) => ({
...e,
tempFilePath: e.path,
fileType: e.type ?? 'file',
}));
return r({ type: 'file', ...res, tempFiles: tmpFiles });
},
fail: (err) => j({ mode: 'chooseMessageFile', data: err }),
});
})
);
};
/**
* 上传
* @param {object} config 参数详情 => https://uniapp.dcloud.net.cn/api/request/network-file.html#uploadfile
* @param {object} exts 选择的文件的数据
* @returns {object} exts + response
*/
export const uploadFile = (config, exts = {}) => {
return new Promise((r, j) => {
uni.uploadFile({
...config,
success: (res) => r({ ...exts, response: JSON.parse(res.data) }),
fail: (err) => j({ mode: 'uploadFile', data: err }),
});
});
};
export const appUploadFile = (config, exts = {}, onprogress) => {
const { url, header, formData } = config;
return new Promise((r, j) => {
const xhr = new XMLHttpRequest();
xhr.open('POST', url, true);
for (let key in header) {
xhr.setRequestHeader(key, header[key]);
}
if (onprogress) {
xhr.upload.onprogress = onprogress;
}
xhr.onreadystatechange = function() {
if (xhr.readyState === 4) {
if (xhr.status === 200) {
r({ ...exts, response: JSON.parse(xhr.responseText) });
} else {
j({ mode: 'uploadFile', data: { data: xhr.responseText, errMsg: 'uploadFile fail.' } });
}
}
}
xhr.send(formData);
});
};

View File

@ -0,0 +1,180 @@
// eslint-disable
export const isObject = (obj) => {
return obj
? Object.prototype.toString.call(obj) === "[object Object]"
: false;
};
export const isArray = (arr) => {
return arr ? Array.isArray(arr) : false;
};
/**
* handle async await
* @param {*} promise promise
*/
export const awaitWrap = (promise) =>
promise.then((res) => [null, res]).catch((err) => [err, {}]);
/**
* 深拷贝
* @param {*} source
*/
export const deepClone = (source) => {
if (!isObject(source) && !isArray(source)) return source;
const targetObj = isArray(source) ? [] : {}; // 判断复制的目标是数组还是对象
for (let keys in source) {
// 遍历目标
if (source.hasOwnProperty(keys)) {
if (source[keys] && typeof source[keys] === "object") {
// 如果值是对象,就递归一下
targetObj[keys] = isArray(source[keys]) ? [] : {};
targetObj[keys] = deepClone(source[keys]);
} else {
// 如果不是,就直接赋值
targetObj[keys] = source[keys];
}
}
}
return targetObj;
};
/**
* @description JS对象深度合并
* @param {object} target 需要拷贝的对象
* @param {object} source 拷贝的来源对象
* @returns {object|boolean} 深度合并后的对象或者false入参有不是对象
*/
export const deepMerge = (target = {}, source = {}) => {
target = deepClone(target);
if (typeof target !== "object" || typeof source !== "object") return false;
for (const prop in source) {
if (!source.hasOwnProperty(prop)) continue;
if (prop in target) {
if (typeof target[prop] !== "object") {
target[prop] = source[prop];
} else if (typeof source[prop] !== "object") {
target[prop] = source[prop];
} else if (target[prop].concat && source[prop].concat) {
target[prop] = target[prop].concat(source[prop]);
} else {
target[prop] = deepMerge(target[prop], source[prop]);
}
} else {
target[prop] = source[prop];
}
}
return target;
};
/**
* 将File对象转为 Blob Url
* @param {File} File对象
* @returns Blob Url
*/
export const fileToBlob = (file) => {
if (!file) return;
const fileType = file.type;
const blob = new Blob([file], { type: fileType || 'application/*' });
const blobUrl = window.URL.createObjectURL(blob);
return blobUrl;
};
/**
* 将File对象转为 base64
* @param {File} File对象
* @returns base64
*/
export const fileToBase64 = (file) => {
if (!file) return;
return new Promise((r, j) => {
const reader = new FileReader();
reader.onloadend = () => {
const base64String = reader.result;
r(base64String);
};
reader.onerror = () => {
j({ mode: 'fileToBase64', data: { errMsg: 'File to base64 fail.' } });
};
reader.readAsDataURL(file);
});
};
/**
* base64转临时路径(改自https://github.com/zhetengbiji/image-tools/blob/master/index.js)
* @param base64
* @returns
*/
function dataUrlToBase64(str) {
var array = str.split(',');
return array[array.length - 1];
};
function biggerThan(v1, v2) {
var v1Array = v1.split('.');
var v2Array = v2.split('.');
var update = false;
for (var index = 0; index < v2Array.length; index++) {
var diff = v1Array[index] - v2Array[index];
if (diff !== 0) {
update = diff > 0;
break;
}
}
return update;
};
var index = 0;
function getNewFileId() {
return Date.now() + String(index++);
};
export const base64ToPath = (base64, name = '') => {
return new Promise((r, j) => {
if (typeof plus !== 'object') {
return j(new Error('not support'));
}
var fileName = '';
if (name) {
const names = name.split('.');
const extName = names.splice(-1);
fileName = `${names.join('.')}-${getNewFileId()}.${extName}`;
} else {
const names = base64.split(',')[0].match(/data\:\S+\/(\S+);/);
if (!names) {
j(new Error('base64 error'));
}
const extName = names[1];
fileName = `${getNewFileId()}.${extName}`;
}
var basePath = '_doc';
var dirPath = 'uniapp_temp';
var filePath = `${basePath}/${dirPath}/${fileName}`;
if (!biggerThan(plus.os.name === 'Android' ? '1.9.9.80627' : '1.9.9.80472', plus.runtime.innerVersion)) {
plus.io.resolveLocalFileSystemURL(basePath, function (entry) {
entry.getDirectory(dirPath, {
create: true,
exclusive: false,
}, function (entry) {
entry.getFile(fileName, {
create: true,
exclusive: false,
}, function (entry) {
entry.createWriter(function (writer) {
writer.onwrite = function () {
r(filePath);
}
writer.onerror = j;
writer.seek(0);
writer.writeAsBinary(dataUrlToBase64(base64));
}, j)
}, j)
}, j)
}, j)
return;
}
var bitmap = new plus.nativeObj.Bitmap(fileName);
bitmap.loadBase64Data(base64, function () {
bitmap.save(filePath, {}, function () {
bitmap.clear();
r(filePath);
}, function (error) {
bitmap.clear();
j(error);
});
}, function (error) {
bitmap.clear();
j(error);
});
});
};