Compare commits

..

17 Commits

Author SHA1 Message Date
Apcallover
bbf6fc57c8 flat: css 2025-12-28 20:19:17 +08:00
yangxiao
544b2dfb4f flat: 修改首页图片 2025-12-28 19:56:51 +08:00
yangxiao
63883356b1 flat: 提交维权申请 2025-12-28 19:48:00 +08:00
bin
2fc924d601 bugfix 2025-12-23 16:42:56 +08:00
bin
44d94f0c10 Merge branch 'main' of http://124.243.245.42:3000/sdz/shihezi-employment-service 2025-12-23 13:40:27 +08:00
bin
e7f9d9c367 文案 2025-12-23 13:40:26 +08:00
Apcallover
bfffd524ed flat: 更改baseUrl 2025-12-23 11:51:18 +08:00
4ae11e31f4 地图优化 2025-12-19 16:45:21 +08:00
bca0d997c6 style 2025-12-19 16:33:15 +08:00
Apcallover
b43eb98a1c flat: ok 2025-12-19 16:13:09 +08:00
Apcallover
44c297aac2 flat: ok 2025-12-19 16:10:39 +08:00
f64c9e5dae bug fix 2025-12-19 16:05:16 +08:00
975835baa5 修改上传html 加入文件校验 2025-12-19 15:48:24 +08:00
1ac524e1f1 fix 2025-12-19 14:47:08 +08:00
7e8bef0cb9 feat : 一体机定位直到成功,其他环境循环2分钟定位, 上传加入文件校验 2025-12-19 14:46:37 +08:00
Apcallover
ce597b182d flat 文件校验 2025-12-19 12:06:35 +08:00
Apcallover
fdd5577c85 flat: 合并代码 2025-12-19 11:35:00 +08:00
41 changed files with 4663 additions and 1656 deletions

16
App.vue
View File

@@ -24,6 +24,7 @@ onLaunch((options) => {
getUserInfo();
useUserStore().changMiniProgramAppStatus(false);
useUserStore().changMachineEnv(false);
useLocationStore().getLocationLoop()//循环获取定位
return;
}
if (isY9MachineType()) {
@@ -32,7 +33,18 @@ onLaunch((options) => {
useUserStore().logOutApp();
useUserStore().changMiniProgramAppStatus(true);
useUserStore().changMachineEnv(true);
useLocationStore().getLocation();
(function loop() {
console.log('📍一体机尝试获取定位')
useLocationStore().getLocation().then(({longitude,latitude})=>{
console.log(`✅一体机获取定位成功:lng:${longitude},lat${latitude}`)
})
.catch(err=>{
console.log('❌一体机获取定位失败,30s后尝试重新获取')
setTimeout(() => {
loop()
}, 3000);
})
})()
uQRListen = new IncreaseRevie();
inactivityManager = new GlobalInactivityManager(handleInactivity, 60 * 1000);
inactivityManager.start();
@@ -40,6 +52,7 @@ onLaunch((options) => {
}
// 正式上线去除此方法
console.warn('浏览器环境');
useLocationStore().getLocationLoop()//循环获取定位
useUserStore().changMiniProgramAppStatus(true);
useUserStore().changMachineEnv(false);
useUserStore().initSeesionId(); //更新
@@ -57,6 +70,7 @@ onLaunch((options) => {
onMounted(() => {});
onShow(() => {
console.log('App Show');
});

View File

@@ -630,6 +630,10 @@ export function sm4Encrypt(key, value, mode = "hex") {
}
}
export function reloadBrowser() {
window.location.reload()
}
export const $api = {
msg,
@@ -679,5 +683,6 @@ export default {
aes_Decrypt,
sm2_Decrypt,
sm2_Encrypt,
safeReLaunch
safeReLaunch,
reloadBrowser
}

View File

@@ -1,6 +1,8 @@
export default {
// baseUrl: 'https://fw.rc.qingdao.gov.cn/rgpp-api/api', // 内网
baseUrl: 'https://qd.zhaopinzao8dian.com/api', // 测试
// baseUrl: 'https://qd.zhaopinzao8dian.com/api', // 测试
baseUrl: '', // 测试
// baseUrl: 'http://36.105.163.21:30083/rgpp/api', // 测试
// baseUrl: 'http://192.168.3.29:8081',
// baseUrl: 'http://10.213.6.207:19010/api',
// 语音转文字
@@ -24,16 +26,18 @@ export default {
virtualJobFair: 'https://web1.isdapp.shandong.gov.cn/jmopen_files/unzip/4a21b3b6efec4f8db2c3d3d5fa51edc9/szjx-rgzn-xnsc/#/pages/metaverse/job_fair',
// 使用模拟定位
UsingSimulatedPositioning: true,
// 是否显示报错信息
showErrorMessage: false,
// 应用信息
appInfo: {
// 应用名称
name: "青岛市就业服务",
name: "石河子市就业服务",
// 爱山东应用标识
loveShandong: 'szjxrgznqzzp',
// 爱山东应用Key
sm2PrivateKey: '0d152c849f10e4469f2af8cedea62004e4f1db7be23c2f7270c1441d8050799d',
// 地区名
areaName: '青岛市',
areaName: '石河子市',
// AI名称
AIName: '小红',
// 应用版本
@@ -78,7 +82,7 @@ export default {
},
shareConfig: {
baseUrl: 'https://qd.zhaopinzao8dian.com',
title: '找工作,用 AI 更高效|青岛市智能求职平台',
title: '找工作,用 AI 更高效|石河子市智能求职平台',
desc: '融合海量岗位、智能简历匹配、竞争力分析,助你精准锁定理想职位!',
imgUrl: 'https://qd.zhaopinzao8dian.com/file/csn/qd_shareLogo.jpg',
},

View File

@@ -1,158 +0,0 @@
import {
ref,
onUnmounted,
readonly
} from 'vue';
const defaultExtractSpeechText = (text) => text;
export function useTTSPlayer() {
const synth = window.speechSynthesis;
const isSpeaking = ref(false);
const isPaused = ref(false);
const utteranceRef = ref(null);
const cleanup = () => {
isSpeaking.value = false;
isPaused.value = false;
utteranceRef.value = null;
};
/**
* @param {string} text - The text to be spoken.
* @param {object} [options] - Optional settings for the speech.
* @param {string} [options.lang] - Language (e.g., 'en-US', 'es-ES').
* @param {number} [options.rate] - Speed (0.1 to 10, default 1).
* @param {number} [options.pitch] - Pitch (0 to 2, default 1).
* @param {SpeechSynthesisVoice} [options.voice] - A specific voice object.
* @param {function(string): string} [options.extractSpeechText] - A function to filter/clean the text before speaking.
*/
const speak = (text, options = {}) => {
if (!synth) {
console.error('SpeechSynthesis API is not supported in this browser.');
return;
}
if (isSpeaking.value) {
synth.cancel();
}
const filteredText = extractSpeechText(text);
if (!filteredText || typeof filteredText !== 'string' || filteredText.trim() === '') {
console.warn('Text to speak is empty after filtering.');
cleanup(); // Ensure state is clean
return;
}
const newUtterance = new SpeechSynthesisUtterance(filteredText); // Use filtered text
utteranceRef.value = newUtterance;
newUtterance.lang = 'zh-CN';
newUtterance.rate = options.rate || 1;
newUtterance.pitch = options.pitch || 1;
if (options.voice) {
newUtterance.voice = options.voice;
}
newUtterance.onstart = () => {
isSpeaking.value = true;
isPaused.value = false;
};
newUtterance.onpause = () => {
isPaused.value = true;
};
newUtterance.onresume = () => {
isPaused.value = false;
};
newUtterance.onend = () => {
cleanup();
};
newUtterance.onerror = (event) => {
console.error('SpeechSynthesis Error:', event.error);
cleanup();
};
synth.speak(newUtterance);
};
const pause = () => {
if (synth && isSpeaking.value && !isPaused.value) {
synth.pause();
}
};
const resume = () => {
if (synth && isPaused.value) {
synth.resume();
}
};
const cancelAudio = () => {
if (synth) {
synth.cancel();
}
cleanup();
};
onUnmounted(() => {
cancelAudio();
});
return {
speak,
pause,
resume,
cancelAudio,
isSpeaking: readonly(isSpeaking),
isPaused: readonly(isPaused),
};
}
function extractSpeechText(markdown) {
const jobRegex = /``` job-json\s*({[\s\S]*?})\s*```/g;
const jobs = [];
let match;
let lastJobEndIndex = 0;
let firstJobStartIndex = -1;
// 提取岗位 json 数据及前后位置
while ((match = jobRegex.exec(markdown)) !== null) {
const jobStr = match[1];
try {
const job = JSON.parse(jobStr);
jobs.push(job);
if (firstJobStartIndex === -1) {
firstJobStartIndex = match.index;
}
lastJobEndIndex = jobRegex.lastIndex;
} catch (e) {
console.warn('JSON 解析失败', e);
}
}
// 提取引导语(第一个 job-json 之前的文字)
const guideText = firstJobStartIndex > 0 ?
markdown.slice(0, firstJobStartIndex).trim() :
'';
// 提取结束语(最后一个 job-json 之后的文字)
const endingText = lastJobEndIndex < markdown.length ?
markdown.slice(lastJobEndIndex).trim() :
'';
// 岗位信息格式化为语音文本
const jobTexts = jobs.map((job, index) => {
return `${index + 1} 个岗位,岗位名称是:${job.jobTitle},公司是:${job.companyName},薪资:${job.salary},地点:${job.location},学历要求:${job.education},经验要求:${job.experience}`;
});
// 拼接总语音内容
const finalTextParts = [];
if (guideText) finalTextParts.push(guideText);
finalTextParts.push(...jobTexts);
if (endingText) finalTextParts.push(endingText);
return finalTextParts.join('\n');
}

View File

@@ -1,6 +1,6 @@
{
"name" : "qingdao-employment-service",
"appid" : "__UNI__2496162",
"appid" : "__UNI__C939371",
"description" : "招聘",
"versionName" : "1.0.0",
"versionCode" : "100",
@@ -83,7 +83,7 @@
"base" : "./",
"mode" : "hash"
},
"title" : "青岛智慧就业服务",
"title" : "石河子智慧就业服务",
"optimization" : {
"treeShaking" : {
"enable" : true

2
package-lock.json generated
View File

@@ -1,5 +1,5 @@
{
"name": "qingdao-employment-service",
"name": "shihezi-employment-service",
"lockfileVersion": 3,
"requires": true,
"packages": {

View File

@@ -8,7 +8,7 @@
<view class="main">
<view class="main-header">
<view class="header-title btn-feel">企业推荐站</view>
<view class="header-text btn-feel">AI智联青岛岗位触手可</view>
<view class="header-text btn-feel">AI智联石河子岗位触手可</view>
<image class="header-img btn-shaky" src="/static/icon/companyBG.png"></image>
</view>
<view class="main-content">

View File

@@ -137,7 +137,7 @@ function changeArea() {
data: [oneDictData('area')],
success: (_, [value]) => {
fromValue.area = value.value;
state.areaText = '青岛市-' + value.label;
state.areaText = '石河子市-' + value.label;
},
});
}

View File

@@ -83,7 +83,7 @@
</view>
<view class="mys-text">
<text>期望工作地</text>
<text>青岛-</text>
<text>石河子-</text>
<dict-Label dictType="area" :value="Number(userInfo.area)"></dict-Label>
</view>
<view class="mys-list">

View File

@@ -82,6 +82,7 @@ const { userInfo } = storeToRefs(useUserStore());
const { getUserResume } = useUserStore();
const { dictLabel, oneDictData } = useDictStore();
const openSelectPopup = inject('openSelectPopup');
import { FileValidator } from '@/utils/fileValidator.js'; //文件校验
const percent = ref('0%');
const state = reactive({
@@ -278,7 +279,15 @@ function selectAvatar() {
sizeType: ['original', 'compressed'],
sourceType: ['album', 'camera'],
count: 1,
success: ({ tempFilePaths, tempFiles }) => {
success: async (res) => {
const tempFilePaths = res.tempFilePaths;
const file = res.tempFiles[0];
const imageValidator = new FileValidator();
try {
await imageValidator.validate(file);
$api.uploadFile(tempFilePaths[0], true)
.then((res) => {
res = JSON.parse(res);
@@ -287,6 +296,9 @@ function selectAvatar() {
.catch((err) => {
$api.msg('上传失败');
});
} catch (error) {
$api.msg(error);
}
},
fail: (error) => {},
});

View File

@@ -54,7 +54,7 @@
</view>
<view class="position-source">
<text>来源&nbsp;</text>
{{ dataType === 2 ? '青岛人才网' : jobInfo.dataSource }}
{{ dataType === 2 ? '石河子人才网' : jobInfo.dataSource }}
</view>
</view>

View File

@@ -0,0 +1,315 @@
<template>
<AppLayout title="申请信息提交" :use-scroll-view="false" :show-bg-image="false">
<template #headerleft>
<view class="btnback">
<image src="@/static/icon/back.png" @click="navBack"></image>
</view>
</template>
<view class="app-container">
<view class="personal-info">
<view class="personal-info-title">个人基本信息</view>
<view class="personal-info-list">
<view class="personal-info-list-l">
<span>*</span>
姓名
</view>
<view class="personal-info-list-r">
<input :value="userInfo.name" class="uni-input" placeholder="请输入你的姓名" />
</view>
</view>
<view class="personal-info-list">
<view class="personal-info-list-l">
<span>*</span>
联系方式
</view>
<view class="personal-info-list-r">
<input :value="userInfo.phone" class="uni-input" placeholder="请输入联系方式" />
</view>
</view>
<view class="personal-info-list">
<view class="personal-info-list-l">
<span>*</span>
身份证号
</view>
<view class="personal-info-list-r">
<input :value="userInfo.idNumber" class="uni-input" placeholder="请输入身份证号" />
</view>
</view>
</view>
<view class="personal-info">
<view class="personal-info-title">工作单位相关信息</view>
<view class="personal-info-list">
<view class="personal-info-list-l">工作单位名称</view>
<view class="personal-info-list-r">
<input class="uni-input" placeholder="请输入工作单位名称" />
</view>
</view>
<view class="personal-info-list">
<view class="personal-info-list-l">工作单位地址</view>
<view class="personal-info-list-r">
<input class="uni-input" placeholder="请输入工作单位地址" />
</view>
</view>
</view>
<view class="personal-info">
<view class="personal-info-title">劳动关系存续期间</view>
<view class="personal-info-list">
<view class="personal-info-list-l">开始时间</view>
<view class="personal-info-list-r" @click="changestartTime">
<!-- <picker mode="date" :value="date" :start="startDate" :end="endDate" @change="bindDateChange">
<view class="uni-input">{{date}}</view>
</picker> -->
<input class="uni-input" :value="startDate" placeholder="开始时间" />
</view>
</view>
<view class="personal-info-list">
<view class="personal-info-list-l">结束时间</view>
<view class="personal-info-list-r" @click="changeendTime">
<input class="uni-input" :value="endDate" placeholder="结束时间" />
</view>
</view>
</view>
<view class="personal-info">
<view class="personal-info-title">侵权情况描述</view>
<view class="personal-info-list">
<view class="personal-info-list-l">描述内容</view>
<view class="personal-info-list-r">
<textarea placeholder="请输入描述内容" />
</view>
</view>
</view>
<view class="personal-info">
<view class="personal-info-title" @click="open">证据材料上传</view>
</view>
<button class="tijiao tijiao-pos" @click="tijiao1">提交申请</button>
<uni-popup ref="popup" type="bottom">
<view class="popup-container">
<view class="popup-container-title"><h3>证据材料上传</h3></view>
<view class="popup-container-list">
<view class="popup-container-list-title">劳动合同</view>
<view style="padding: 10rpx">
<uni-file-picker file-mediatype="all">
<button class="button" size="mini">选择文件</button>
</uni-file-picker>
</view>
</view>
<view class="popup-container-list">
<view>工资条</view>
<view style="padding: 10rpx">
<uni-file-picker file-mediatype="all">
<button class="button1" size="mini">选择文件</button>
</uni-file-picker>
</view>
</view>
<view class="popup-container-list">
<view>考勤记录</view>
<view style="padding: 10rpx">
<uni-file-picker file-mediatype="all">
<button class="button2" size="mini">选择文件</button>
</uni-file-picker>
</view>
</view>
<view class="popup-container-list">
<view>沟通记录截图</view>
<view style="padding: 10rpx">
<uni-file-picker file-mediatype="all">
<button class="button3" size="mini">选择文件</button>
</uni-file-picker>
</view>
</view>
<view style="padding-top: 20rpx">
<button class="tijiao" @click="tijiao">提交材料</button>
</view>
</view>
</uni-popup>
<DatePicker ref="datePicker" />
</view>
</AppLayout>
</template>
<script setup>
import { reactive, inject, computed, watch, ref, onMounted } from 'vue';
import { onLoad, onShow } from '@dcloudio/uni-app';
const { $api, debounce, throttle, navBack, safeReLaunch } = inject('globalFunction');
import { storeToRefs } from 'pinia';
import useUserStore from '@/stores/useUserStore';
import DatePicker from '@/components/DatePicker/DatePicker.vue';
import { navTo } from '@/common/globalFunction';
const { userInfo } = storeToRefs(useUserStore());
// 获取时间选择器组件的引用
const datePicker = ref();
const popup = ref();
const active = ref(1);
const startDate = ref(null);
const endDate = ref(null);
// 选择开始时间
const changestartTime = () => {
datePicker.value.open({
title: '选择开始时间',
success: (selectedDate) => {
startDate.value = selectedDate;
},
});
};
// 选择结束时间
const changeendTime = () => {
datePicker.value.open({
title: '选择结束时间',
success: (selectedDate) => {
endDate.value = selectedDate;
if (startDate.value && new Date(startDate.value) > new Date(selectedDate)) {
endDate.value = '';
$api.msg('结束时间不能小于开始时间!');
}
},
});
};
const open = () => {
popup.value.open('bottom');
};
const tijiao = () => {
popup.value.close();
};
onMounted(() => {});
const tijiao1 = () => {
safeReLaunch('/pages/index/index');
};
</script>
<style lang="stylus" scoped>
.btnback{
width: 64rpx;
height: 64rpx;
}
image {
height: 100%;
width: 100%;
}
.app-container{
width: 100%;
height: 100%;
background: #EEE;
display: flex;
padding-top: 10rpx;
flex-direction: column;
.personal-info {
width: 100%;
background: #fff;
padding: 20rpx;
margin-bottom: 10rpx;
.personal-info-title {
width: 100%;
// padding: 10rpx 0;
font-size: 28rpx;
font-weight: bold;
}
.personal-info-list {
width: 100%;
display: flex;
padding: 10rpx 0;
border-bottom: 1px solid #EEE;
.personal-info-list-l {
width: 200rpx;
color: #B0B0B0;
font-weight: bolder !important;
padding-right: 20rpx;
span {
color: red;
}
}
.personal-info-list-r {
flex: 1;
}
}
}
}
.steps {
height: 200rpx;
}
.popup-container {
height: 800rpx;
width: 100%;
height: 100%;
overflow: auto;
background: #fff;
.popup-container-title {
width: 100%;
text-align: center;
height: 80rpx;
line-height: 80rpx;
color: #B0B0B0;
font-weight: bolder !important;
}
}
.popup-container-list {
padding: 0 20rpx;
padding-top: 20rpx;
border-bottom: 1px solid #EEE;
}
.popup-container-list-title {
font-size: 28rpx;
font-weight: blod;
}
.button {
border: none !important;
background: #EEF2FF;
color: #4338CA;
}
.button1 {
border: none !important;
background: #F0FDF4;
color: #288B4C;
}
.button2 {
border: none !important;
background: #FEFCE8;
color: #A76C17;
}
.button3 {
border: none !important;
background: #FEF2F2;
color: #C23B3B;
}
.tijiao {
width: 80%;
background: #58BE6B;
color: #fff;
}
.tijiao-pos {
position: absolute;
bottom: 100rpx;
left: 10%;
}
</style>

View File

@@ -35,7 +35,7 @@
<!-- <view>到岗2025-11-02</view> -->
<view></view>
<view>
地点青岛-
地点石河子-
<dict-Label dictType="area" :value="Number(userInfo.area)"></dict-Label>
</view>
</view>

View File

@@ -4,7 +4,7 @@
{
"path": "pages/index/index",
"style": {
"navigationBarTitleText": "青岛智慧就业平台",
"navigationBarTitleText": "石河子智慧就业平台",
// #ifdef H5
"navigationStyle": "custom"
// #endif
@@ -227,6 +227,14 @@
"navigationBarBackgroundColor": "#FFFFFF",
"navigationStyle": "custom"
}
},
{
"path": "pages/rightsProtectionApplication/rightsProtectionApplication",
"style": {
"navigationBarTitleText": "申请信息提交",
"navigationBarBackgroundColor": "#FFFFFF",
"navigationStyle": "custom"
}
}
]
}],

View File

@@ -4,12 +4,12 @@
<!-- 顶部头部区域 -->
<view class="container-header">
<view class="header-top">
<view class="header-btnLf button-click" @click="seemsg(0)" :class="{ active: state.current === 0 }">
<!-- <view class="header-btnLf button-click" @click="seemsg(0)" :class="{ active: state.current === 0 }">
现场招聘
</view>
<view v-if="!isMachineEnv" class="header-btnLf button-click" @click="seemsg(1)" :class="{ active: state.current === 1 }">
VR虚拟招聘会
</view>
</view> -->
</view>
<view class="header-input btn-feel">
<my-icons class="iconsearch" color="#666666" type="search" size="36"></my-icons>
@@ -116,18 +116,18 @@ const { longitudeVal, latitudeVal } = storeToRefs(useLocationStore());
import useUserStore from '@/stores/useUserStore';
const { isMachineEnv } = storeToRefs(useUserStore());
const { $api, navTo, cloneDeep, debounce } = inject('globalFunction');
import useScreenStore from '@/stores/useScreenStore'
import useScreenStore from '@/stores/useScreenStore';
const screenStore = useScreenStore()
const showTabbar = ref(false)
const screenStore = useScreenStore();
const showTabbar = ref(false);
watch(
() => screenStore.isWideScreen,
(newVal) => {
showTabbar.value = newVal
showTabbar.value = newVal;
},
{ immediate: true }
)
);
const weekList = ref([]);
const fairList = ref([]);

View File

@@ -55,7 +55,7 @@
<header class="head">
<view class="main-header">
<image src="/static/icon/Hamburger-button.png" @click="toggleDrawer"></image>
<view class="title">青岛市岗位推荐</view>
<view class="title">石河子市岗位推荐</view>
<image src="/static/icon/Comment-one.png" @click="addNewDialogue"></image>
</view>
</header>

View File

@@ -7,9 +7,9 @@
<view class="chat-background" v-fade:600="!messages.length">
<!-- #endif -->
<image class="backlogo" src="/static/icon/backAI.png"></image>
<view class="back-rowTitle">欢迎使用青岛AI智能求职</view>
<view class="back-rowTitle">欢迎使用石河子AI智能求职</view>
<view class="back-rowText">
我可以根据您的简历和求职需求帮你精准匹配青岛市互联网招聘信息对比招聘信息的优缺点提供面试指导等请把你的任务交给我吧~
我可以根据您的简历和求职需求帮你精准匹配石河子市互联网招聘信息对比招聘信息的优缺点提供面试指导等请把你的任务交给我吧~
</view>
<view class="back-rowh3">猜你所想</view>
<view
@@ -273,9 +273,7 @@ import useScreenStore from '@/stores/useScreenStore'
const screenStore = useScreenStore();
// 系统功能hook和阿里云hook
import { useAudioRecorder } from '@/hook/useRealtimeRecorder.js';
// import { useAudioRecorder } from '@/hook/useSystemSpeechReader.js';
import { useTTSPlayer } from '@/hook/useTTSPlayer.js';
// import { useTTSPlayer } from '@/hook/useSystemPlayer.js';
// 全局
const { $api, navTo, throttle } = inject('globalFunction');
const emit = defineEmits(['onConfirm']);
@@ -283,6 +281,8 @@ const { messages, isTyping, textInput, chatSessionID } = storeToRefs(useChatGrou
import successIcon from '@/static/icon/success.png';
import useUserStore from '@/stores/useUserStore';
const { isMachineEnv } = storeToRefs(useUserStore());
import { FileValidator } from '@/utils/fileValidator.js'; //文件校验
// hook
// 语音识别
const {
@@ -538,10 +538,14 @@ function uploadCamera(type = 'camera') {
count: 1, //默认9
sizeType: ['original', 'compressed'], //可以指定是原图还是压缩图,默认二者都有
sourceType: [type], //从相册选择
success: function (res) {
success: async (res)=> {
const tempFilePaths = res.tempFilePaths;
const file = res.tempFiles[0];
// 继续上传
const imageValidator = new FileValidator()
try {
await imageValidator.validate(file)
$api.uploadFile(tempFilePaths[0], true).then((resData) => {
resData = JSON.parse(resData);
console.log(file.type,'++')
@@ -554,6 +558,9 @@ function uploadCamera(type = 'camera') {
textInput.value = state.uploadFileTips;
}
});
} catch (error) {
$api.msg(error)
}
},
});
}
@@ -562,15 +569,17 @@ function getUploadFile(type = 'camera') {
if (VerifyNumberFiles()) return;
uni.chooseFile({
count: 1,
success: (res) => {
success: async(res) => {
const tempFilePaths = res.tempFilePaths;
const file = res.tempFiles[0];
const allowedTypes = config.allowedFileTypes || [];
const size = $api.formatFileSize(file.size);
if (!allowedTypes.includes(file.type)) {
return $api.msg('仅支持 txt md word pdf ppt csv excel 格式类型');
}
// 继续上传
const imageValidator = new FileValidator({allowedExtensions:config.allowedFileTypes})
try{
await imageValidator.validate(file)
$api.uploadFile(tempFilePaths[0], true).then((resData) => {
resData = JSON.parse(resData);
filesList.value.push({
@@ -581,6 +590,9 @@ function getUploadFile(type = 'camera') {
});
textInput.value = state.uploadFileTips;
});
}catch(error){
$api.msg(error)
}
},
});
}
@@ -737,22 +749,22 @@ function refreshMarkdown(index) {
}
const jobSearchQueries = [
'青岛有哪些薪资 12K 以上的岗位适合我?',
'青岛 3 年工作经验能找到哪些 12K 以上的工作?',
'青岛哪些公司在招聘,薪资范围在 12K 以上?',
'青岛有哪些企业提供 15K 以上的岗位?',
'青岛哪些公司在招 3-5 年经验的岗位?',
'我有三年的工作经验,能否推荐一些适合我的青岛的国企 岗位?',
'青岛国企目前在招聘哪些岗位?',
'青岛有哪些适合 3 年经验的国企岗位?',
'青岛国企招聘的岗位待遇如何?',
'青岛国企岗位的薪资水平是多少?',
'青岛哪些国企支持双休 & 五险一金完善?',
'青岛有哪些公司支持远程办公?',
'青岛有哪些外企的岗位,薪资 12K 以上的多吗?',
'青岛哪些企业在招聘 Web3.0 相关岗位?',
'青岛哪些岗位支持海外远程?薪资如何?',
'青岛招聘 AI/大数据相关岗位的公司有哪些?',
'石河子有哪些薪资 12K 以上的岗位适合我?',
'石河子 3 年工作经验能找到哪些 12K 以上的工作?',
'石河子哪些公司在招聘,薪资范围在 12K 以上?',
'石河子有哪些企业提供 15K 以上的岗位?',
'石河子哪些公司在招 3-5 年经验的岗位?',
'我有三年的工作经验,能否推荐一些适合我的石河子的国企 岗位?',
'石河子国企目前在招聘哪些岗位?',
'石河子有哪些适合 3 年经验的国企岗位?',
'石河子国企招聘的岗位待遇如何?',
'石河子国企岗位的薪资水平是多少?',
'石河子哪些国企支持双休 & 五险一金完善?',
'石河子有哪些公司支持远程办公?',
'石河子有哪些外企的岗位,薪资 12K 以上的多吗?',
'石河子哪些企业在招聘 Web3.0 相关岗位?',
'石河子哪些岗位支持海外远程?薪资如何?',
'石河子招聘 AI/大数据相关岗位的公司有哪些?',
];
function changeQueries(value) {

View File

@@ -190,7 +190,7 @@ function makeQrcode() {
// 外网测试环境
pathPrefix = '/app';
} else if (host.includes('fw.rc.qingdao.gov.cn')) {
// 青岛政务网环境
// 石河子政务网环境
pathPrefix = '/rgpp-api/all-in-one';
} else {
pathPrefix = '';

View File

@@ -8,10 +8,16 @@
>
<view class="nav-hidden">
<view class="container-search">
<image class="bg-text" mode="widthFix" src="@/static/icon/index-text-bg.png"></image>
<!-- <image class="bg-text" mode="widthFix" src="@/static/icon/index-text-bg.png"></image> -->
<image class="bg-text" mode="scaleToFill" src="@/static/imgs/shihezi.jpg"></image>
<view class="gradient-overlay"></view>
<view class="search-inner">
<view class="inner-left">
<image class="bg-text2" mode="widthFix" src="@/static/icon/index-text-bg2.png"></image>
<!-- <image
class="bg-text2"
@click="reloadBrowser()"
src="@/static/icon/index-text-bg2.png"
></image> -->
<view class="search-input button-click" @click="navTo('/pages/search/search')">
<image class="icon" src="@/static/icon/index-search.png"></image>
<text class="inpute">请告诉我想找什么工作</text>
@@ -28,8 +34,8 @@
<view class="item-box">
<view class="box-l">
<view class="item1 button-click" @click="handleItemClick('素质测评')">
<view class="title">AI素质测评</view>
<view class="des">提高个人素质</view>
<view class="title">劳动力维权</view>
<view class="des">维权申请</view>
<image class="bg-text" mode="widthFix" src="@/static/icon/item-bg-text.png"></image>
<image class="bg-img" src="@/static/icon/item-bg-img1.png"></image>
</view>
@@ -183,7 +189,7 @@
</view>
</view>
<!-- <view class="falls-card-company">
青岛
石河子
<dict-Label dictType="area" :value="job.jobLocationAreaCode"></dict-Label>
</view> -->
<view class="falls-card-pepleNumber">
@@ -254,7 +260,7 @@
import { reactive, inject, watch, ref, onMounted, watchEffect, nextTick, getCurrentInstance } from 'vue';
import img from '@/static/icon/filter.png';
import dictLabel from '@/components/dict-Label/dict-Label.vue';
const { $api, navTo, vacanciesTo, formatTotal, throttle } = inject('globalFunction');
const { $api, navTo, vacanciesTo, formatTotal, throttle, reloadBrowser } = inject('globalFunction');
import { onLoad, onShow } from '@dcloudio/uni-app';
import { storeToRefs } from 'pinia';
import useUserStore from '@/stores/useUserStore';
@@ -271,7 +277,6 @@ const recommedIndexDb = useRecommedIndexedDBStore();
import config from '@/config';
import AIMatch from './AIMatch.vue';
const { proxy } = getCurrentInstance();
const maskFirstEntry = ref(true);
@@ -363,7 +368,7 @@ onMounted(() => {
let firstEntry = uni.getStorageSync('firstEntry') === false ? false : true; // 默认未读
maskFirstEntry.value = firstEntry;
getMatchTags();
console.log(isMachineEnv.value,'+++++++++')
// console.log(isMachineEnv.value, '+++++++++');
});
async function getMatchTags() {
@@ -427,9 +432,10 @@ const handleTagClick = (tagInfo) => {
const handleItemClick = (item) => {
switch (item) {
case '素质测评':
lightAppJssdk.navigation.hide({
url: config.Quality_assessment_URL,
});
// lightAppJssdk.navigation.hide({
// url: config.Quality_assessment_URL,
// });
navTo('/packageA/pages/rightsProtectionApplication/rightsProtectionApplication');
break;
case '就业指导':
lightAppJssdk.navigation.hide({
@@ -466,7 +472,6 @@ const { columnCount, columnSpace } = useColumnCount(() => {
getJobRecommend('refresh');
nextTick(() => {
waterfallsFlowRef.value?.refresh?.();
useLocationStore().getLocation();
});
});
@@ -815,6 +820,16 @@ defineExpose({ loadData });
// width: 4rpx
// height: 20rpx
.gradient-overlay {
position: absolute;
bottom: 0;
left: 0;
right: 0;
height: 100px;
background: linear-gradient(to top, rgba(255, 255, 255, 0.8), transparent);
pointer-events: none;
}
.app-container
width: 100%;
height: calc(100vh - var(--window-top) - var(--status-bar-height) - var(--window-bottom));
@@ -830,9 +845,10 @@ defineExpose({ loadData });
padding:60rpx 0 0rpx;
position: relative
.bg-text
position :absolute
position: absolute;
width:100%;
top:10%;
height: 100%;
top: 0%;
left:0
.search-inner
position relative;
@@ -844,7 +860,7 @@ defineExpose({ loadData });
.inner-left
flex:1
overflow:hidden
display:flex
// display:flex
flex-direction: column;
.bg-robot
@@ -854,9 +870,10 @@ defineExpose({ loadData });
margin-bottom:-13%
.bg-text2
width:100%;
height:145rpx;
.search-input
flex:1
margin-top:8%;
margin-top:39%;
margin-bottom:18%;
display: flex
align-items: center;

View File

@@ -129,7 +129,6 @@ const { columnCount, columnSpace } = useColumnCount(() => {
pageSize.value = 10 * (columnCount.value - 1);
nextTick(() => {
waterfallsFlowRef.value?.refresh?.();
useLocationStore().getLocation();
});
});

View File

@@ -80,7 +80,7 @@
</view>
<view class="btns">
<button class="wxlogin" @click="loginTest">内测登录</button>
<view class="wxaddress">青岛市公共就业和人才服务中心</view>
<view class="wxaddress">石河子市公共就业和人才服务中心</view>
</view>
</template>
<template v-slot:tab1>
@@ -331,7 +331,7 @@ function changeEducation() {
maskClick: true,
data: [oneDictData('education')],
success: (_, [value]) => {
fromValue.area = value.value;
fromValue.education = value.value;
state.educationText = value.label;
},
});
@@ -344,7 +344,7 @@ function changeArea() {
data: [oneDictData('area')],
success: (_, [value]) => {
fromValue.area = value.value;
state.areaText = '青岛市-' + value.label;
state.areaText = '石河子市-' + value.label;
},
});
}

View File

@@ -2,13 +2,14 @@
<scroll-view :scroll-y="true" class="nearby-scroll" @scrolltolower="scrollBottom">
<view class="nearby-map" @touchmove.stop.prevent>
<map
style="width: 100%; height: 410rpx"
style="width: 100%; height: 690rpx"
:latitude="latitudeVal"
:longitude="longitudeVal"
:markers="mapCovers"
:circles="mapCircles"
:controls="mapControls"
@controltap="handleControl"
:scale="mapScale"
></map>
<view class="nearby-select">
<view class="select-view" @click="changeRangeShow">
@@ -106,16 +107,18 @@ const tMap = ref();
const progress = ref();
const mapCovers = ref([]);
const mapCircles = ref([]);
const mapScale = ref(14.5)
const mapControls = ref([
{
id: 1,
position: {
// 控件位置
left: customSystem.systemInfo.screenWidth - 48 - 14,
top: 320,
width: 48,
height: 48,
left: customSystem.systemInfo.screenWidth - uni.upx2px(75 + 30),
top: uni.upx2px(655 - 75 - 30),
width: uni.upx2px(75),
height: uni.upx2px(75),
},
width:100,
iconPath: LocationPng, // 控件图标
},
]);
@@ -148,6 +151,8 @@ function changeRangeShow() {
function changeRadius(item) {
console.log(item);
if(item > 1) mapScale.value = 14.5 - item * 0.3
else mapScale.value = 14.5
pageState.search.radius = item;
rangeShow.value = false;
progressChange(item);
@@ -221,27 +226,23 @@ onMounted(() => {
});
function getInit() {
useLocationStore()
.getLocation()
.then((res) => {
mapCovers.value = [
{
latitude: res.latitude,
longitude: res.longitude,
latitude: latitudeVal.value,
longitude: longitudeVal.value,
iconPath: point2,
},
];
mapCircles.value = [
{
latitude: res.latitude,
longitude: res.longitude,
latitude: latitudeVal.value,
longitude:longitudeVal.value,
radius: 1000,
fillColor: '#1c52fa25',
color: '#256BFA',
},
];
getJobList('refresh');
});
}
function progressChange(value) {
@@ -363,7 +364,7 @@ defineExpose({ loadData, handleFilterConfirm });
height: 100%;
background: #f4f4f4;
.nearby-map
height: 400rpx;
height: 655rpx;
background: #e8e8e8;
overflow: hidden
.nearby-list

View File

@@ -151,7 +151,6 @@ const { columnCount, columnSpace } = useColumnCount(() => {
pageSize.value = 10 * (columnCount.value - 1);
nextTick(() => {
waterfallsFlowRef.value?.refresh?.();
useLocationStore().getLocation();
});
});

568
pnpm-lock.yaml generated Normal file
View File

@@ -0,0 +1,568 @@
lockfileVersion: '9.0'
settings:
autoInstallPeers: true
excludeLinksFromLockfile: false
importers:
.:
devDependencies:
unplugin-vue-components:
specifier: ^0.26.0
version: 0.26.0(@babel/parser@7.28.5)(vue@3.5.26)
packages:
'@antfu/utils@0.7.10':
resolution: {integrity: sha512-+562v9k4aI80m1+VuMHehNJWLOFjBnXn3tdOitzD0il5b7smkSBal4+a3oKiQTbrwMmN/TBUMDvbdoWDehgOww==}
'@babel/helper-string-parser@7.27.1':
resolution: {integrity: sha512-qMlSxKbpRlAridDExk92nSobyDdpPijUq2DW6oDnUqd0iOGxmQjyqhMIihI9+zv4LPyZdRje2cavWPbCbWm3eA==}
engines: {node: '>=6.9.0'}
'@babel/helper-validator-identifier@7.28.5':
resolution: {integrity: sha512-qSs4ifwzKJSV39ucNjsvc6WVHs6b7S03sOh2OcHF9UHfVPqWWALUsNUVzhSBiItjRZoLHx7nIarVjqKVusUZ1Q==}
engines: {node: '>=6.9.0'}
'@babel/parser@7.28.5':
resolution: {integrity: sha512-KKBU1VGYR7ORr3At5HAtUQ+TV3SzRCXmA/8OdDZiLDBIZxVyzXuztPjfLd3BV1PRAQGCMWWSHYhL0F8d5uHBDQ==}
engines: {node: '>=6.0.0'}
hasBin: true
'@babel/types@7.28.5':
resolution: {integrity: sha512-qQ5m48eI/MFLQ5PxQj4PFaprjyCTLI37ElWMmNs0K8Lk3dVeOdNpB3ks8jc7yM5CDmVC73eMVk/trk3fgmrUpA==}
engines: {node: '>=6.9.0'}
'@jridgewell/sourcemap-codec@1.5.5':
resolution: {integrity: sha512-cYQ9310grqxueWbl+WuIUIaiUaDcj7WOq5fVhEljNVgRfOUhY9fy2zTvfoqWsnebh8Sl70VScFbICvJnLKB0Og==}
'@nodelib/fs.scandir@2.1.5':
resolution: {integrity: sha512-vq24Bq3ym5HEQm2NKCr3yXDwjc7vTsEThRDnkp2DK9p1uqLR+DHurm/NOTo0KG7HYHU7eppKZj3MyqYuMBf62g==}
engines: {node: '>= 8'}
'@nodelib/fs.stat@2.0.5':
resolution: {integrity: sha512-RkhPPp2zrqDAQA/2jNhnztcPAlv64XdhIp7a7454A5ovI7Bukxgt7MX7udwAu3zg1DcpPU0rz3VV1SeaqvY4+A==}
engines: {node: '>= 8'}
'@nodelib/fs.walk@1.2.8':
resolution: {integrity: sha512-oGB+UxlgWcgQkgwo8GcEGwemoTFt3FIO9ababBmaGwXIoBKZ+GTy0pP185beGg7Llih/NSHSV2XAs1lnznocSg==}
engines: {node: '>= 8'}
'@rollup/pluginutils@5.3.0':
resolution: {integrity: sha512-5EdhGZtnu3V88ces7s53hhfK5KSASnJZv8Lulpc04cWO3REESroJXg73DFsOmgbU2BhwV0E20bu2IDZb3VKW4Q==}
engines: {node: '>=14.0.0'}
peerDependencies:
rollup: ^1.20.0||^2.0.0||^3.0.0||^4.0.0
peerDependenciesMeta:
rollup:
optional: true
'@types/estree@1.0.8':
resolution: {integrity: sha512-dWHzHa2WqEXI/O1E9OjrocMTKJl2mSrEolh1Iomrv6U+JuNwaHXsXx9bLu5gG7BUWFIN0skIQJQ/L1rIex4X6w==}
'@vue/compiler-core@3.5.26':
resolution: {integrity: sha512-vXyI5GMfuoBCnv5ucIT7jhHKl55Y477yxP6fc4eUswjP8FG3FFVFd41eNDArR+Uk3QKn2Z85NavjaxLxOC19/w==}
'@vue/compiler-dom@3.5.26':
resolution: {integrity: sha512-y1Tcd3eXs834QjswshSilCBnKGeQjQXB6PqFn/1nxcQw4pmG42G8lwz+FZPAZAby6gZeHSt/8LMPfZ4Rb+Bd/A==}
'@vue/compiler-sfc@3.5.26':
resolution: {integrity: sha512-egp69qDTSEZcf4bGOSsprUr4xI73wfrY5oRs6GSgXFTiHrWj4Y3X5Ydtip9QMqiCMCPVwLglB9GBxXtTadJ3mA==}
'@vue/compiler-ssr@3.5.26':
resolution: {integrity: sha512-lZT9/Y0nSIRUPVvapFJEVDbEXruZh2IYHMk2zTtEgJSlP5gVOqeWXH54xDKAaFS4rTnDeDBQUYDtxKyoW9FwDw==}
'@vue/reactivity@3.5.26':
resolution: {integrity: sha512-9EnYB1/DIiUYYnzlnUBgwU32NNvLp/nhxLXeWRhHUEeWNTn1ECxX8aGO7RTXeX6PPcxe3LLuNBFoJbV4QZ+CFQ==}
'@vue/runtime-core@3.5.26':
resolution: {integrity: sha512-xJWM9KH1kd201w5DvMDOwDHYhrdPTrAatn56oB/LRG4plEQeZRQLw0Bpwih9KYoqmzaxF0OKSn6swzYi84e1/Q==}
'@vue/runtime-dom@3.5.26':
resolution: {integrity: sha512-XLLd/+4sPC2ZkN/6+V4O4gjJu6kSDbHAChvsyWgm1oGbdSO3efvGYnm25yCjtFm/K7rrSDvSfPDgN1pHgS4VNQ==}
'@vue/server-renderer@3.5.26':
resolution: {integrity: sha512-TYKLXmrwWKSodyVuO1WAubucd+1XlLg4set0YoV+Hu8Lo79mp/YMwWV5mC5FgtsDxX3qo1ONrxFaTP1OQgy1uA==}
peerDependencies:
vue: 3.5.26
'@vue/shared@3.5.26':
resolution: {integrity: sha512-7Z6/y3uFI5PRoKeorTOSXKcDj0MSasfNNltcslbFrPpcw6aXRUALq4IfJlaTRspiWIUOEZbrpM+iQGmCOiWe4A==}
acorn@8.15.0:
resolution: {integrity: sha512-NZyJarBfL7nWwIq+FDL6Zp/yHEhePMNnnJ0y3qfieCrmNvYct8uvtiV41UvlSe6apAfk0fY1FbWx+NwfmpvtTg==}
engines: {node: '>=0.4.0'}
hasBin: true
anymatch@3.1.3:
resolution: {integrity: sha512-KMReFUr0B4t+D+OBkjR3KYqvocp2XaSzO55UcB6mgQMd3KbcE+mWTyvVV7D/zsdEbNnV6acZUutkiHQXvTr1Rw==}
engines: {node: '>= 8'}
balanced-match@1.0.2:
resolution: {integrity: sha512-3oSeUO0TMV67hN1AmbXsK4yaqU7tjiHlbxRDZOpH0KW9+CeX4bRAaX0Anxt0tx2MrpRpWwQaPwIlISEJhYU5Pw==}
binary-extensions@2.3.0:
resolution: {integrity: sha512-Ceh+7ox5qe7LJuLHoY0feh3pHuUDHAcRUeyL2VYghZwfpkNIy/+8Ocg0a3UuSoYzavmylwuLWQOf3hl0jjMMIw==}
engines: {node: '>=8'}
brace-expansion@2.0.2:
resolution: {integrity: sha512-Jt0vHyM+jmUBqojB7E1NIYadt0vI0Qxjxd2TErW94wDz+E2LAm5vKMXXwg6ZZBTHPuUlDgQHKXvjGBdfcF1ZDQ==}
braces@3.0.3:
resolution: {integrity: sha512-yQbXgO/OSZVD2IsiLlro+7Hf6Q18EJrKSEsdoMzKePKXct3gvD8oLcOQdIzGupr5Fj+EDe8gO/lxc1BzfMpxvA==}
engines: {node: '>=8'}
chokidar@3.6.0:
resolution: {integrity: sha512-7VT13fmjotKpGipCW9JEQAusEPE+Ei8nl6/g4FBAmIm0GOOLMua9NDDo/DWp0ZAxCr3cPq5ZpBqmPAQgDda2Pw==}
engines: {node: '>= 8.10.0'}
csstype@3.2.3:
resolution: {integrity: sha512-z1HGKcYy2xA8AGQfwrn0PAy+PB7X/GSj3UVJW9qKyn43xWa+gl5nXmU4qqLMRzWVLFC8KusUX8T/0kCiOYpAIQ==}
debug@4.4.3:
resolution: {integrity: sha512-RGwwWnwQvkVfavKVt22FGLw+xYSdzARwm0ru6DhTVA3umU5hZc28V3kO4stgYryrTlLpuvgI9GiijltAjNbcqA==}
engines: {node: '>=6.0'}
peerDependencies:
supports-color: '*'
peerDependenciesMeta:
supports-color:
optional: true
entities@7.0.0:
resolution: {integrity: sha512-FDWG5cmEYf2Z00IkYRhbFrwIwvdFKH07uV8dvNy0omp/Qb1xcyCWp2UDtcwJF4QZZvk0sLudP6/hAu42TaqVhQ==}
engines: {node: '>=0.12'}
estree-walker@2.0.2:
resolution: {integrity: sha512-Rfkk/Mp/DL7JVje3u18FxFujQlTNR2q6QfMSMB7AvCBx91NGj/ba3kCfza0f6dVDbw7YlRf/nDrn7pQrCCyQ/w==}
fast-glob@3.3.3:
resolution: {integrity: sha512-7MptL8U0cqcFdzIzwOTHoilX9x5BrNqye7Z/LuC7kCMRio1EMSyqRK3BEAUD7sXRq4iT4AzTVuZdhgQ2TCvYLg==}
engines: {node: '>=8.6.0'}
fastq@1.19.1:
resolution: {integrity: sha512-GwLTyxkCXjXbxqIhTsMI2Nui8huMPtnxg7krajPJAjnEG/iiOS7i+zCtWGZR9G0NBKbXKh6X9m9UIsYX/N6vvQ==}
fill-range@7.1.1:
resolution: {integrity: sha512-YsGpe3WHLK8ZYi4tWDg2Jy3ebRz2rXowDxnld4bkQB00cc/1Zw9AWnC0i9ztDJitivtQvaI9KaLyKrc+hBW0yg==}
engines: {node: '>=8'}
fsevents@2.3.3:
resolution: {integrity: sha512-5xoDfX+fL7faATnagmWPpbFtwh/R77WmMMqqHGS65C3vvB0YHrgF+B1YmZ3441tMj5n63k0212XNoJwzlhffQw==}
engines: {node: ^8.16.0 || ^10.6.0 || >=11.0.0}
os: [darwin]
function-bind@1.1.2:
resolution: {integrity: sha512-7XHNxH7qX9xG5mIwxkhumTox/MIRNcOgDrxWsMt2pAr23WHp6MrRlN7FBSFpCpr+oVO0F744iUgR82nJMfG2SA==}
glob-parent@5.1.2:
resolution: {integrity: sha512-AOIgSQCepiJYwP3ARnGx+5VnTu2HBYdzbGP45eLw1vr3zB3vZLeyed1sC9hnbcOc9/SrMyM5RPQrkGz4aS9Zow==}
engines: {node: '>= 6'}
hasown@2.0.2:
resolution: {integrity: sha512-0hJU9SCPvmMzIBdZFqNPXWa6dqh7WdH0cII9y+CyS8rG3nL48Bclra9HmKhVVUHyPWNH5Y7xDwAB7bfgSjkUMQ==}
engines: {node: '>= 0.4'}
is-binary-path@2.1.0:
resolution: {integrity: sha512-ZMERYes6pDydyuGidse7OsHxtbI7WVeUEozgR/g7rd0xUimYNlvZRE/K2MgZTjWy725IfelLeVcEM97mmtRGXw==}
engines: {node: '>=8'}
is-core-module@2.16.1:
resolution: {integrity: sha512-UfoeMA6fIJ8wTYFEUjelnaGI67v6+N7qXJEvQuIGa99l4xsCruSYOVSQ0uPANn4dAzm8lkYPaKLrrijLq7x23w==}
engines: {node: '>= 0.4'}
is-extglob@2.1.1:
resolution: {integrity: sha512-SbKbANkN603Vi4jEZv49LeVJMn4yGwsbzZworEoyEiutsN3nJYdbO36zfhGJ6QEDpOZIFkDtnq5JRxmvl3jsoQ==}
engines: {node: '>=0.10.0'}
is-glob@4.0.3:
resolution: {integrity: sha512-xelSayHH36ZgE7ZWhli7pW34hNbNl8Ojv5KVmkJD4hBdD3th8Tfk9vYasLM+mXWOZhFkgZfxhLSnrwRr4elSSg==}
engines: {node: '>=0.10.0'}
is-number@7.0.0:
resolution: {integrity: sha512-41Cifkg6e8TylSpdtTpeLVMqvSBEVzTttHvERD741+pnZ8ANv0004MRL43QKPDlK9cGvNp6NZWZUBlbGXYxxng==}
engines: {node: '>=0.12.0'}
local-pkg@0.4.3:
resolution: {integrity: sha512-SFppqq5p42fe2qcZQqqEOiVRXl+WCP1MdT6k7BDEW1j++sp5fIY+/fdRQitvKgB5BrBcmrs5m/L0v2FrU5MY1g==}
engines: {node: '>=14'}
magic-string@0.30.21:
resolution: {integrity: sha512-vd2F4YUyEXKGcLHoq+TEyCjxueSeHnFxyyjNp80yg0XV4vUhnDer/lvvlqM/arB5bXQN5K2/3oinyCRyx8T2CQ==}
merge2@1.4.1:
resolution: {integrity: sha512-8q7VEgMJW4J8tcfVPy8g09NcQwZdbwFEqhe/WZkoIzjn/3TGDwtOCYtXGxA3O8tPzpczCCDgv+P2P5y00ZJOOg==}
engines: {node: '>= 8'}
micromatch@4.0.8:
resolution: {integrity: sha512-PXwfBhYu0hBCPw8Dn0E+WDYb7af3dSLVWKi3HGv84IdF4TyFoC0ysxFd0Goxw7nSv4T/PzEJQxsYsEiFCKo2BA==}
engines: {node: '>=8.6'}
minimatch@9.0.5:
resolution: {integrity: sha512-G6T0ZX48xgozx7587koeX9Ys2NYy6Gmv//P89sEte9V9whIapMNF4idKxnW2QtCcLiTWlb/wfCabAtAFWhhBow==}
engines: {node: '>=16 || 14 >=14.17'}
ms@2.1.3:
resolution: {integrity: sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA==}
nanoid@3.3.11:
resolution: {integrity: sha512-N8SpfPUnUp1bK+PMYW8qSWdl9U+wwNWI4QKxOYDy9JAro3WMX7p2OeVRF9v+347pnakNevPmiHhNmZ2HbFA76w==}
engines: {node: ^10 || ^12 || ^13.7 || ^14 || >=15.0.1}
hasBin: true
normalize-path@3.0.0:
resolution: {integrity: sha512-6eZs5Ls3WtCisHWp9S2GUy8dqkpGi4BVSz3GaqiE6ezub0512ESztXUwUB6C6IKbQkY2Pnb/mD4WYojCRwcwLA==}
engines: {node: '>=0.10.0'}
path-parse@1.0.7:
resolution: {integrity: sha512-LDJzPVEEEPR+y48z93A0Ed0yXb8pAByGWo/k5YYdYgpY2/2EsOsksJrq7lOHxryrVOn1ejG6oAp8ahvOIQD8sw==}
picocolors@1.1.1:
resolution: {integrity: sha512-xceH2snhtb5M9liqDsmEw56le376mTZkEX/jEb/RxNFyegNul7eNslCXP9FDj/Lcu0X8KEyMceP2ntpaHrDEVA==}
picomatch@2.3.1:
resolution: {integrity: sha512-JU3teHTNjmE2VCGFzuY8EXzCDVwEqB2a8fsIvwaStHhAWJEeVd1o1QD80CU6+ZdEXXSLbSsuLwJjkCBWqRQUVA==}
engines: {node: '>=8.6'}
picomatch@4.0.3:
resolution: {integrity: sha512-5gTmgEY/sqK6gFXLIsQNH19lWb4ebPDLA4SdLP7dsWkIXHWlG66oPuVvXSGFPppYZz8ZDZq0dYYrbHfBCVUb1Q==}
engines: {node: '>=12'}
postcss@8.5.6:
resolution: {integrity: sha512-3Ybi1tAuwAP9s0r1UQ2J4n5Y0G05bJkpUIO0/bI9MhwmD70S5aTWbXGBwxHrelT+XM1k6dM0pk+SwNkpTRN7Pg==}
engines: {node: ^10 || ^12 || >=14}
queue-microtask@1.2.3:
resolution: {integrity: sha512-NuaNSa6flKT5JaSYQzJok04JzTL1CA6aGhv5rfLW3PgqA+M2ChpZQnAC8h8i4ZFkBS8X5RqkDBHA7r4hej3K9A==}
readdirp@3.6.0:
resolution: {integrity: sha512-hOS089on8RduqdbhvQ5Z37A0ESjsqz6qnRcffsMU3495FuTdqSm+7bhJ29JvIOsBDEEnan5DPu9t3To9VRlMzA==}
engines: {node: '>=8.10.0'}
resolve@1.22.11:
resolution: {integrity: sha512-RfqAvLnMl313r7c9oclB1HhUEAezcpLjz95wFH4LVuhk9JF/r22qmVP9AMmOU4vMX7Q8pN8jwNg/CSpdFnMjTQ==}
engines: {node: '>= 0.4'}
hasBin: true
reusify@1.1.0:
resolution: {integrity: sha512-g6QUff04oZpHs0eG5p83rFLhHeV00ug/Yf9nZM6fLeUrPguBTkTQOdpAWWspMh55TZfVQDPaN3NQJfbVRAxdIw==}
engines: {iojs: '>=1.0.0', node: '>=0.10.0'}
run-parallel@1.2.0:
resolution: {integrity: sha512-5l4VyZR86LZ/lDxZTR6jqL8AFE2S0IFLMP26AbjsLVADxHdhB/c0GUsH+y39UfCi3dzz8OlQuPmnaJOMoDHQBA==}
source-map-js@1.2.1:
resolution: {integrity: sha512-UXWMKhLOwVKb728IUtQPXxfYU+usdybtUrK/8uGE8CQMvrhOpwvzDBwj0QhSL7MQc7vIsISBG8VQ8+IDQxpfQA==}
engines: {node: '>=0.10.0'}
supports-preserve-symlinks-flag@1.0.0:
resolution: {integrity: sha512-ot0WnXS9fgdkgIcePe6RHNk1WA8+muPa6cSjeR3V8K27q9BB1rTE3R1p7Hv0z1ZyAc8s6Vvv8DIyWf681MAt0w==}
engines: {node: '>= 0.4'}
to-regex-range@5.0.1:
resolution: {integrity: sha512-65P7iz6X5yEr1cwcgvQxbbIw7Uk3gOy5dIdtZ4rDveLqhrdJP+Li/Hx6tyK0NEb+2GCyneCMJiGqrADCSNk8sQ==}
engines: {node: '>=8.0'}
unplugin-vue-components@0.26.0:
resolution: {integrity: sha512-s7IdPDlnOvPamjunVxw8kNgKNK8A5KM1YpK5j/p97jEKTjlPNrA0nZBiSfAKKlK1gWZuyWXlKL5dk3EDw874LQ==}
engines: {node: '>=14'}
peerDependencies:
'@babel/parser': ^7.15.8
'@nuxt/kit': ^3.2.2
vue: 2 || 3
peerDependenciesMeta:
'@babel/parser':
optional: true
'@nuxt/kit':
optional: true
unplugin@1.16.1:
resolution: {integrity: sha512-4/u/j4FrCKdi17jaxuJA0jClGxB1AvU2hw/IuayPc4ay1XGaJs/rbb4v5WKwAjNifjmXK9PIFyuPiaK8azyR9w==}
engines: {node: '>=14.0.0'}
vue@3.5.26:
resolution: {integrity: sha512-SJ/NTccVyAoNUJmkM9KUqPcYlY+u8OVL1X5EW9RIs3ch5H2uERxyyIUI4MRxVCSOiEcupX9xNGde1tL9ZKpimA==}
peerDependencies:
typescript: '*'
peerDependenciesMeta:
typescript:
optional: true
webpack-virtual-modules@0.6.2:
resolution: {integrity: sha512-66/V2i5hQanC51vBQKPH4aI8NMAcBW59FVBs+rC7eGHupMyfn34q7rZIE+ETlJ+XTevqfUhVVBgSUNSW2flEUQ==}
snapshots:
'@antfu/utils@0.7.10': {}
'@babel/helper-string-parser@7.27.1': {}
'@babel/helper-validator-identifier@7.28.5': {}
'@babel/parser@7.28.5':
dependencies:
'@babel/types': 7.28.5
'@babel/types@7.28.5':
dependencies:
'@babel/helper-string-parser': 7.27.1
'@babel/helper-validator-identifier': 7.28.5
'@jridgewell/sourcemap-codec@1.5.5': {}
'@nodelib/fs.scandir@2.1.5':
dependencies:
'@nodelib/fs.stat': 2.0.5
run-parallel: 1.2.0
'@nodelib/fs.stat@2.0.5': {}
'@nodelib/fs.walk@1.2.8':
dependencies:
'@nodelib/fs.scandir': 2.1.5
fastq: 1.19.1
'@rollup/pluginutils@5.3.0':
dependencies:
'@types/estree': 1.0.8
estree-walker: 2.0.2
picomatch: 4.0.3
'@types/estree@1.0.8': {}
'@vue/compiler-core@3.5.26':
dependencies:
'@babel/parser': 7.28.5
'@vue/shared': 3.5.26
entities: 7.0.0
estree-walker: 2.0.2
source-map-js: 1.2.1
'@vue/compiler-dom@3.5.26':
dependencies:
'@vue/compiler-core': 3.5.26
'@vue/shared': 3.5.26
'@vue/compiler-sfc@3.5.26':
dependencies:
'@babel/parser': 7.28.5
'@vue/compiler-core': 3.5.26
'@vue/compiler-dom': 3.5.26
'@vue/compiler-ssr': 3.5.26
'@vue/shared': 3.5.26
estree-walker: 2.0.2
magic-string: 0.30.21
postcss: 8.5.6
source-map-js: 1.2.1
'@vue/compiler-ssr@3.5.26':
dependencies:
'@vue/compiler-dom': 3.5.26
'@vue/shared': 3.5.26
'@vue/reactivity@3.5.26':
dependencies:
'@vue/shared': 3.5.26
'@vue/runtime-core@3.5.26':
dependencies:
'@vue/reactivity': 3.5.26
'@vue/shared': 3.5.26
'@vue/runtime-dom@3.5.26':
dependencies:
'@vue/reactivity': 3.5.26
'@vue/runtime-core': 3.5.26
'@vue/shared': 3.5.26
csstype: 3.2.3
'@vue/server-renderer@3.5.26(vue@3.5.26)':
dependencies:
'@vue/compiler-ssr': 3.5.26
'@vue/shared': 3.5.26
vue: 3.5.26
'@vue/shared@3.5.26': {}
acorn@8.15.0: {}
anymatch@3.1.3:
dependencies:
normalize-path: 3.0.0
picomatch: 2.3.1
balanced-match@1.0.2: {}
binary-extensions@2.3.0: {}
brace-expansion@2.0.2:
dependencies:
balanced-match: 1.0.2
braces@3.0.3:
dependencies:
fill-range: 7.1.1
chokidar@3.6.0:
dependencies:
anymatch: 3.1.3
braces: 3.0.3
glob-parent: 5.1.2
is-binary-path: 2.1.0
is-glob: 4.0.3
normalize-path: 3.0.0
readdirp: 3.6.0
optionalDependencies:
fsevents: 2.3.3
csstype@3.2.3: {}
debug@4.4.3:
dependencies:
ms: 2.1.3
entities@7.0.0: {}
estree-walker@2.0.2: {}
fast-glob@3.3.3:
dependencies:
'@nodelib/fs.stat': 2.0.5
'@nodelib/fs.walk': 1.2.8
glob-parent: 5.1.2
merge2: 1.4.1
micromatch: 4.0.8
fastq@1.19.1:
dependencies:
reusify: 1.1.0
fill-range@7.1.1:
dependencies:
to-regex-range: 5.0.1
fsevents@2.3.3:
optional: true
function-bind@1.1.2: {}
glob-parent@5.1.2:
dependencies:
is-glob: 4.0.3
hasown@2.0.2:
dependencies:
function-bind: 1.1.2
is-binary-path@2.1.0:
dependencies:
binary-extensions: 2.3.0
is-core-module@2.16.1:
dependencies:
hasown: 2.0.2
is-extglob@2.1.1: {}
is-glob@4.0.3:
dependencies:
is-extglob: 2.1.1
is-number@7.0.0: {}
local-pkg@0.4.3: {}
magic-string@0.30.21:
dependencies:
'@jridgewell/sourcemap-codec': 1.5.5
merge2@1.4.1: {}
micromatch@4.0.8:
dependencies:
braces: 3.0.3
picomatch: 2.3.1
minimatch@9.0.5:
dependencies:
brace-expansion: 2.0.2
ms@2.1.3: {}
nanoid@3.3.11: {}
normalize-path@3.0.0: {}
path-parse@1.0.7: {}
picocolors@1.1.1: {}
picomatch@2.3.1: {}
picomatch@4.0.3: {}
postcss@8.5.6:
dependencies:
nanoid: 3.3.11
picocolors: 1.1.1
source-map-js: 1.2.1
queue-microtask@1.2.3: {}
readdirp@3.6.0:
dependencies:
picomatch: 2.3.1
resolve@1.22.11:
dependencies:
is-core-module: 2.16.1
path-parse: 1.0.7
supports-preserve-symlinks-flag: 1.0.0
reusify@1.1.0: {}
run-parallel@1.2.0:
dependencies:
queue-microtask: 1.2.3
source-map-js@1.2.1: {}
supports-preserve-symlinks-flag@1.0.0: {}
to-regex-range@5.0.1:
dependencies:
is-number: 7.0.0
unplugin-vue-components@0.26.0(@babel/parser@7.28.5)(vue@3.5.26):
dependencies:
'@antfu/utils': 0.7.10
'@rollup/pluginutils': 5.3.0
chokidar: 3.6.0
debug: 4.4.3
fast-glob: 3.3.3
local-pkg: 0.4.3
magic-string: 0.30.21
minimatch: 9.0.5
resolve: 1.22.11
unplugin: 1.16.1
vue: 3.5.26
optionalDependencies:
'@babel/parser': 7.28.5
transitivePeerDependencies:
- rollup
- supports-color
unplugin@1.16.1:
dependencies:
acorn: 8.15.0
webpack-virtual-modules: 0.6.2
vue@3.5.26:
dependencies:
'@vue/compiler-dom': 3.5.26
'@vue/compiler-sfc': 3.5.26
'@vue/runtime-dom': 3.5.26
'@vue/server-renderer': 3.5.26(vue@3.5.26)
'@vue/shared': 3.5.26
webpack-virtual-modules@0.6.2: {}

Binary file not shown.

Before

Width:  |  Height:  |  Size: 2.3 KiB

After

Width:  |  Height:  |  Size: 1.6 MiB

BIN
static/imgs/shihezi.jpg Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 67 KiB

170
static/js/fileValidator.js Normal file
View File

@@ -0,0 +1,170 @@
const KNOWN_SIGNATURES = {
png: '89504E470D0A1A0A',
jpg: 'FFD8FF',
jpeg: 'FFD8FF',
gif: '47494638',
webp: '52494646',
docx: '504B0304',
xlsx: '504B0304',
pptx: '504B0304',
doc: 'D0CF11E0',
xls: 'D0CF11E0',
ppt: 'D0CF11E0',
pdf: '25504446',
txt: 'TYPE_TEXT',
csv: 'TYPE_TEXT',
md: 'TYPE_TEXT',
json: 'TYPE_TEXT',
};
export class FileValidator {
version = '1.0.0';
signs = Object.keys(KNOWN_SIGNATURES);
constructor(options = {}) {
this.maxSizeMB = options.maxSizeMB || 10;
if (options.allowedExtensions && Array.isArray(options.allowedExtensions)) {
this.allowedConfig = {};
options.allowedExtensions.forEach((ext) => {
const key = ext.toLowerCase();
if (KNOWN_SIGNATURES[key]) {
this.allowedConfig[key] = KNOWN_SIGNATURES[key];
} else {
console.warn(`[FileValidator] 未知的文件类型: .${key},已忽略`);
}
});
} else {
this.allowedConfig = {
...KNOWN_SIGNATURES,
};
}
}
_isValidUTF8(buffer) {
try {
const decoder = new TextDecoder('utf-8', {
fatal: true,
});
decoder.decode(buffer);
return true;
} catch (e) {
return false;
}
}
_bufferToHex(buffer) {
return Array.prototype.map
.call(new Uint8Array(buffer), (x) => ('00' + x.toString(16)).slice(-2))
.join('')
.toUpperCase();
}
_countCSVRows(buffer) {
const decoder = new TextDecoder('utf-8');
const text = decoder.decode(buffer);
let rowCount = 0;
let inQuote = false;
let len = text.length;
for (let i = 0; i < len; i++) {
const char = text[i];
if (char === '"') {
inQuote = !inQuote;
} else if (char === '\n' && !inQuote) {
rowCount++;
}
}
if (len > 0 && text[len - 1] !== '\n') {
rowCount++;
}
return rowCount;
}
_validateTextContent(buffer, extension) {
let contentStr = '';
try {
const decoder = new TextDecoder('utf-8', {
fatal: true,
});
contentStr = decoder.decode(buffer);
} catch (e) {
console.warn('UTF-8 解码失败', e);
return false;
}
if (contentStr.includes('\0')) {
return false;
}
if (extension === 'json') {
try {
JSON.parse(contentStr);
} catch (e) {
console.warn('无效的 JSON 格式');
return false;
}
}
return true;
}
validate(file) {
return new Promise((resolve, reject) => {
if (!file || !file.name) return reject('无效的文件对象');
if (file.size > this.maxSizeMB * 1024 * 1024) {
return reject(`文件大小超出限制 (最大 ${this.maxSizeMB}MB)`);
}
const fileName = file.name.toLowerCase();
const extension = fileName.substring(fileName.lastIndexOf('.') + 1);
const expectedMagic = this.allowedConfig[extension];
if (!expectedMagic) {
return reject(`不支持的文件格式: .${extension}`);
}
const reader = new FileReader();
reader.onload = (e) => {
const buffer = e.target.result;
let isSafe = false;
if (expectedMagic === 'TYPE_TEXT') {
if (this._validateTextContent(buffer, extension)) {
isSafe = true;
} else {
if (extension === 'json') {
return reject(`文件异常:不是有效的 JSON 文件`);
}
return reject(`文件异常:.${extension} 包含非法二进制内容或编码错误`);
}
if (extension === 'csv' && this.csvMaxRows > 0) {
const rows = this._countCSVRows(buffer);
if (rows > this.csvMaxRows) {
return reject(`CSV 行数超出限制 (当前 ${rows} 行,最大允许 ${this.csvMaxRows} 行)`);
}
}
} else {
const fileHeader = this._bufferToHex(buffer.slice(0, 8));
if (fileHeader.startsWith(expectedMagic)) {
isSafe = true;
} else {
return reject(`文件可能已被篡改 (真实类型与 .${extension} 不符)`);
}
}
if (isSafe) resolve(true);
};
reader.onerror = () => reject('文件读取失败,无法校验');
if (expectedMagic === 'TYPE_TEXT' && extension === 'json') {
reader.readAsArrayBuffer(file);
} else {
reader.readAsArrayBuffer(file.slice(0, 2048));
}
});
}
}
// 【demo】
// 如果传入了 allowedExtensions则只使用传入的否则使用全部 KNOWN_SIGNATURES
// const imageValidator = new FileValidator({
// maxSizeMB: 5,
// allowedExtensions: ['png', 'jpg', 'jpeg'],
// });
// imageValidator
// .validate(file)
// .then(() => {
// statusDiv.textContent = `检测通过: ${file.name}`;
// statusDiv.style.color = 'green';
// console.log('图片校验通过,开始上传...');
// // upload(file)...
// })
// .catch((err) => {
// statusDiv.textContent = `检测失败: ${err}`;
// statusDiv.style.color = 'red';
// });

View File

@@ -2,11 +2,11 @@
<html lang="zh-CN">
<head>
<meta charset="utf-8" />
<title>找工作,用 AI 更高效|青岛市智能求职平台</title>
<title>找工作,用 AI 更高效|石河子市智能求职平台</title>
<meta name="viewport" content="width=device-width, initial-scale=1" />
<!-- 微信分享卡片标签(动态填充) -->
<meta property="og:title" content="找工作,用 AI 更高效|青岛市智能求职平台" />
<meta property="og:title" content="找工作,用 AI 更高效|石河子市智能求职平台" />
<meta property="og:description" content="融合海量岗位、智能简历匹配、竞争力分析,助你精准锁定理想职位!" />
<meta property="og:image" content="https://qd.zhaopinzao8dian.com/file/csn/qd_shareLogo.jpg" />
<meta property="og:url" content="https://qd.zhaopinzao8dian.com" />

View File

@@ -2,11 +2,10 @@
<html lang="zh-CN">
<head>
<meta charset="UTF-8" />
<meta
name="viewport"
content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no, viewport-fit=cover"
/>
<meta name="viewport"
content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no, viewport-fit=cover" />
<title>文件上传</title>
<style>
* {
margin: 0;
@@ -172,6 +171,7 @@
opacity: 0;
transform: translateY(10px);
}
to {
opacity: 1;
transform: translateY(0);
@@ -341,6 +341,7 @@
0% {
transform: rotate(0deg);
}
100% {
transform: rotate(360deg);
}
@@ -352,30 +353,61 @@
font-weight: 500;
}
/* 状态提示框容器 */
.status-messages-container {
pointer-events: none;
width: 100%;
}
/* 状态提示框 */
.status-message {
position: fixed;
top: 50%;
left: 20px;
right: 20px;
transform: translateY(-50%);
background: rgb(238, 238, 238);
border-radius: 16px;
padding: 30px 25px;
text-align: center;
box-shadow: 0 20px 60px rgba(0, 0, 0, 0.2);
z-index: 1001;
box-shadow: 0 20px 60px rgba(0, 0, 0, 0.4);
margin: 0 auto 20px;
display: none;
animation: popUp 0.3s ease;
max-width: 85%;
pointer-events: auto;
position: fixed;
top: 45%;
left: 0;
right: 0;
z-index: 1001;
transform: translateY(-50%);
}
/* 点击关闭按钮 */
.status-message .close-btn {
position: absolute;
top: 10px;
right: 10px;
background: none;
border: none;
font-size: 20px;
cursor: pointer;
color: #666;
width: 30px;
height: 30px;
border-radius: 50%;
display: flex;
align-items: center;
justify-content: center;
}
.status-message .close-btn:hover {
background: rgba(0, 0, 0, 0.1);
}
@keyframes popUp {
from {
opacity: 0;
transform: translateY(-40%) scale(0.9);
}
to {
opacity: 1;
transform: translateY(-50%) scale(1);
}
}
@@ -583,13 +615,8 @@
<div class="upload-icon">📁</div>
<div class="upload-text" id="uploadText">点击选择文件</div>
<div class="upload-hint" id="uploadHint">支持图片、文档、文本等格式</div>
<input
type="file"
id="fileInput"
class="file-input"
multiple
accept="image/*,.pdf,.doc,.docx,.xls,.xlsx,.csv,.ppt,.pptx,.txt,.md"
/>
<input type="file" id="fileInput" class="file-input" multiple
accept="image/*,.pdf,.doc,.docx,.xls,.xlsx,.csv,.ppt,.pptx,.txt,.md" />
</div>
</div>
@@ -615,13 +642,8 @@
<div class="loading-text" id="loadingText">上传中,请稍候...</div>
</div>
<!-- 状态提示框 -->
<div class="status-message" id="statusMessage">
<span class="status-icon" id="statusIcon"></span>
<h3 class="status-title" id="statusTitle">上传成功!</h3>
<p class="status-desc" id="statusDesc">文件已成功上传到电脑端</p>
<button class="status-btn" id="statusBtn">完成</button>
</div>
<!-- 状态提示框容器 -->
<div class="status-messages-container" id="statusMessagesContainer"></div>
<!-- 图片预览模态框 -->
<div class="image-preview-modal" id="imagePreviewModal">
@@ -629,7 +651,13 @@
<button class="close-preview" id="closePreview">×</button>
</div>
<script>
<script type="module">
import {
FileValidator
} from './js/FileValidator.js'; //文件校验JS
// 创建文件校验器实例
const fileValidator = new FileValidator();
// 获取URL中的参数
const urlParams = new URLSearchParams(window.location.search);
const sessionId = urlParams.get('sessionId');
@@ -655,11 +683,7 @@
const uploadBtn = document.getElementById('uploadBtn');
const loadingOverlay = document.getElementById('loadingOverlay');
const loadingText = document.getElementById('loadingText');
const statusMessage = document.getElementById('statusMessage');
const statusIcon = document.getElementById('statusIcon');
const statusTitle = document.getElementById('statusTitle');
const statusDesc = document.getElementById('statusDesc');
const statusBtn = document.getElementById('statusBtn');
const statusMessagesContainer = document.getElementById('statusMessagesContainer');
const imagePreviewModal = document.getElementById('imagePreviewModal');
const previewImage = document.getElementById('previewImage');
const closePreview = document.getElementById('closePreview');
@@ -673,6 +697,8 @@
let isUploading = false;
let uploadedCount = 0; // 已上传的总文件数量
let statusMessageCount = 0; // 弹窗计数器
// 初始化
function init() {
// 更新限制提示文本
@@ -688,12 +714,28 @@
fileInput.addEventListener('change', handleFileSelect);
clearBtn.addEventListener('click', clearAllFiles);
uploadBtn.addEventListener('click', startUpload);
statusBtn.addEventListener('click', hideStatus);
closePreview.addEventListener('click', () => {
imagePreviewModal.classList.remove('show');
document.body.style.overflow = '';
});
// 添加事件委托来处理状态消息的关闭按钮
statusMessagesContainer.addEventListener('click', (e) => {
if (e.target.matches('[data-action="close"]')) {
const messageId = e.target.dataset.messageId;
closeStatusMessage(messageId);
}
});
// 添加事件委托来处理删除按钮
fileList.addEventListener('click', (e) => {
if (e.target.classList.contains('remove-btn')) {
const name = e.target.dataset.name;
const size = parseInt(e.target.dataset.size);
removeFile(name, size);
}
});
// 图片预览模态框点击外部关闭
imagePreviewModal.addEventListener('click', (e) => {
if (e.target === imagePreviewModal) {
@@ -706,7 +748,9 @@
setupDragAndDrop();
// 防止页面滚动
document.body.addEventListener('touchmove', preventScroll, { passive: false });
document.body.addEventListener('touchmove', preventScroll, {
passive: false
});
// 更新UI
updateUI();
@@ -795,7 +839,7 @@
}
// 处理文件
function handleFiles(files) {
async function handleFiles(files) {
// 检查是否已达到总文件数量上限
if (MAX_FILE_COUNT > 0 && uploadedCount >= MAX_FILE_COUNT) {
showError(`已超过文件上传总数限制(${MAX_FILE_COUNT}个)`);
@@ -816,6 +860,7 @@
}
for (let file of files) {
console.log(file);
// 检查是否已达到本次选择的文件数量上限
if (selectedFiles.length >= MAX_FILE_COUNT) {
showError(`最多只能选择 ${MAX_FILE_COUNT} 个文件,已忽略多余文件`);
@@ -839,12 +884,18 @@
continue;
}
// 添加到文件列表
fileValidator
.validate(file)
.then(() => {
console.log(1111);
selectedFiles.push(file);
addFileToList(file);
}
updateUI();
})
.catch((err) => {
showError(file.name + err);
});
}
}
// 检查是否为图片文件
@@ -888,12 +939,26 @@
};
return icons[ext] || icons.default;
}
// 移除文件
function removeFile(name, size) {
selectedFiles = selectedFiles.filter((f) => !(f.name === name && f.size === size));
const fileItem = document.querySelector(`.file-item[data-name="${name}"]`);
if (fileItem) {
fileItem.style.animation = 'slideIn 0.3s ease reverse';
setTimeout(() => {
fileItem.remove();
updateUI();
}, 150);
}
}
// 添加文件到列表
function addFileToList(file) {
const li = document.createElement('li');
li.className = 'file-item';
li.dataset.name = file.name;
li.dataset.size = file.size; // 添加 size 到 dataset
// 检查是否为图片
const isImage = isImageType(file) && isImageFile(file.name);
@@ -901,7 +966,7 @@
// 获取文件图标
const fileIcon = getFileIcon(file.name);
// 创建HTML
// 创建HTML(移除 onclick改为 data 属性)
li.innerHTML = `
<div class="file-icon-container" id="icon-${escapeHtml(file.name)}">
${
@@ -917,7 +982,7 @@
<div class="file-progress-bar" id="progress-${escapeHtml(file.name)}"></div>
</div>
</div>
<button class="remove-btn" onclick="removeFile('${escapeHtml(file.name)}', ${file.size})">×</button>
<button class="remove-btn" data-name="${escapeHtml(file.name)}" data-size="${file.size}">×</button>
`;
fileList.appendChild(li);
@@ -934,7 +999,6 @@
});
}
}
// 生成缩略图
function generateThumbnail(file, containerId) {
const reader = new FileReader();
@@ -977,20 +1041,6 @@
return parseFloat((bytes / Math.pow(k, i)).toFixed(1)) + ' ' + sizes[i];
}
// 移除文件
function removeFile(name, size) {
selectedFiles = selectedFiles.filter((f) => !(f.name === name && f.size === size));
const fileItem = document.querySelector(`.file-item[data-name="${name}"]`);
if (fileItem) {
fileItem.style.animation = 'slideIn 0.3s ease reverse';
setTimeout(() => {
fileItem.remove();
updateUI();
}, 150);
}
}
// 清空所有文件
function clearAllFiles() {
selectedFiles = [];
@@ -1037,7 +1087,8 @@
fileInput.disabled = true;
} else {
uploadText.textContent = '点击选择文件';
uploadHint.innerHTML = `支持图片、文档、文本等格式<br />最多${MAX_FILE_COUNT}个文件每个不超过10MB<br />已上传: ${uploadedCount}/${MAX_FILE_COUNT}`;
uploadHint.innerHTML =
`支持图片、文档、文本等格式<br />最多${MAX_FILE_COUNT}个文件每个不超过10MB<br />已上传: ${uploadedCount}/${MAX_FILE_COUNT}`;
fileInput.disabled = false;
}
@@ -1197,43 +1248,129 @@
document.body.style.overflow = '';
}
// 显示成功提示
function showSuccess(message) {
statusMessage.className = 'status-message status-success';
statusIcon.textContent = '✅';
statusTitle.textContent = '上传成功!';
statusDesc.textContent = message;
statusMessage.style.display = 'block';
document.body.style.overflow = 'hidden';
// 创建状态提示
function createStatusMessage(type, title, desc, autoClose = false, closeTime = 3000) {
// 创建唯一的ID
const messageId = 'status-' + Date.now() + '-' + Math.random().toString(36).substr(2, 9);
// 计算当前弹窗的偏移量每个弹窗下移20px
const offset = statusMessageCount * 40;
// 创建弹窗HTML添加自定义的偏移样式
const messageHtml = `
<div class="status-message status-${type}" id="${messageId}"
data-message-id="${messageId}"
style="margin-top: ${offset}px;">
<button class="close-btn" data-action="close" data-message-id="${messageId}">×</button>
<span class="status-icon">${type === 'success' ? '✅' : '❌'}</span>
<h3 class="status-title">${escapeHtml(title)}</h3>
<p class="status-desc">${escapeHtml(desc)}</p>
<button class="status-btn" data-action="close" data-message-id="${messageId}">完成</button>
</div>
`;
// 添加到容器
statusMessagesContainer.innerHTML += messageHtml;
// 显示弹窗
const messageElement = document.getElementById(messageId);
messageElement.style.display = 'block';
// 增加弹窗计数
statusMessageCount++;
// 自动关闭
if (autoClose) {
setTimeout(() => {
closeStatusMessage(messageId);
}, closeTime);
}
// 显示错误提示
function showError(message) {
statusMessage.className = 'status-message status-error';
statusIcon.textContent = '❌';
statusTitle.textContent = '出错了';
statusDesc.textContent = message;
statusMessage.style.display = 'block';
document.body.style.overflow = 'hidden';
// 限制最大显示数量最多显示5个
const messages = statusMessagesContainer.querySelectorAll('.status-message');
if (messages.length > 5) {
// 移除最早的消息
const oldestMessage = messages[0];
closeStatusMessage(oldestMessage.id);
}
// 隐藏状态提示
function hideStatus() {
statusMessage.style.display = 'none';
return messageId;
}
// 关闭状态提示框
function closeStatusMessage(messageId) {
const messageElement = document.getElementById(messageId);
if (messageElement) {
// 添加淡出动画
messageElement.style.animation = 'popUp 0.3s ease reverse';
messageElement.style.opacity = '0';
setTimeout(() => {
messageElement.remove();
// 减少弹窗计数
statusMessageCount--;
// 重新计算并更新剩余弹窗的位置
updateRemainingStatusMessages();
// 检查是否还有消息显示
const remainingMessages = statusMessagesContainer.querySelectorAll('.status-message');
if (remainingMessages.length === 0) {
document.body.style.overflow = '';
}
}, 300);
}
}
// 更新剩余弹窗的位置
function updateRemainingStatusMessages() {
const messages = statusMessagesContainer.querySelectorAll('.status-message');
messages.forEach((message, index) => {
const offset = index * 20; // 每个弹窗下移20px
message.style.marginTop = `${offset}px`;
});
}
// 隐藏所有状态提示
function hideAllStatus() {
const messages = statusMessagesContainer.querySelectorAll('.status-message');
messages.forEach((message) => {
closeStatusMessage(message.id);
});
document.body.style.overflow = '';
}
// 防止页面滚动
// 显示成功提示(创建新弹窗)
function showSuccess(message, options = {}) {
const {
autoClose = true, closeTime = 3000
} = options;
return createStatusMessage('success', '上传成功!', message, autoClose, closeTime);
}
// 显示错误提示(创建新弹窗)
function showError(message, options = {}) {
const {
autoClose = false, closeTime = 5000
} = options;
return createStatusMessage('error', '出错了', message, autoClose, closeTime);
}
// 修改防止页面滚动函数
function preventScroll(e) {
const messages = statusMessagesContainer.querySelectorAll('.status-message');
const hasMessages = messages.length > 0;
if (
loadingOverlay.classList.contains('show') ||
statusMessage.style.display === 'block' ||
hasMessages ||
imagePreviewModal.classList.contains('show')
) {
e.preventDefault();
}
}
// HTML转义
function escapeHtml(text) {
const div = document.createElement('div');

View File

@@ -9,10 +9,17 @@ import {
} from '@/common/globalFunction.js'
import config from '../config';
const defalutLongLat = {
longitude: 120.382665,
latitude: 36.066938,
}
const useLocationStore = defineStore("location", () => {
// 定义状态
const longitudeVal = ref(null) // 经度
const latitudeVal = ref(null) //纬度
const timer = ref(null)
const count = ref(0)
function getLocation() { // 获取经纬度两个平台
return new Promise((resole, reject) => {
@@ -25,49 +32,57 @@ const useLocationStore = defineStore("location", () => {
resole(data)
},
fail: function(data) {
longitudeVal.value = 120.382665
latitudeVal.value = 36.066938
resole({
longitude: 120.382665,
latitude: 36.066938
})
longitudeVal.value = defalutLongLat.longitude
latitudeVal.value = defalutLongLat.latitude
resole(defalutLongLat)
msg('用户位置获取失败')
console.log('失败3', data)
}
})
} else {
uni.getLocation({
type: 'gcj02',
highAccuracyExpireTime: 3000,
isHighAccuracy: true,
timeout: 2000,
// highAccuracyExpireTime: 3000,
// isHighAccuracy: true,
// timeout: 2000,
success: function(data) {
longitudeVal.value = Number(data.longitude)
latitudeVal.value = Number(data.latitude)
resole(data)
},
fail: function(data) {
longitudeVal.value = 120.382665
latitudeVal.value = 36.066938
resole({
longitude: 120.382665,
latitude: 36.066938
})
longitudeVal.value = defalutLongLat.longitude
latitudeVal.value = defalutLongLat.latitude
resole(defalutLongLat)
msg('用户位置获取失败')
console.log('失败2', data)
}
});
}
} catch (e) {
longitudeVal.value = 120.382665
latitudeVal.value = 36.066938
resole({
longitude: 120.382665,
latitude: 36.066938
})
longitudeVal.value = defalutLongLat.longitude
latitudeVal.value = defalutLongLat.latitude
resole(defalutLongLat)
msg('测试环境,使用模拟定位')
console.log('失败', data)
console.log('失败1', e)
}
})
}
function getLocationLoop(gap = 1000 * 60 * 2) {
console.log(`🔄开始循环获取定位,间隔:${Math.floor(gap/1000)}`)
const run = () => {
count.value++
console.log(`📍第${count.value}次获取定位`)
getLocation()
}
run()
timer.value = setInterval(run,gap);
}
function clearGetLocationLoop(params) {
clearInterval(timer.value)
timer.value = null
}
function longitude() {
return longitudeVal.value
@@ -80,9 +95,10 @@ const useLocationStore = defineStore("location", () => {
// 导入
return {
getLocation,
getLocationLoop,
clearGetLocationLoop,
longitudeVal,
latitudeVal
latitudeVal,
}
}, {
unistorage: true,

View File

@@ -0,0 +1,91 @@
## 1.1.32025-12-03
- 修复: 腾讯云目录错误导致的上传错误问题
## 1.1.22025-09-17
- 修复 设置readonly属性后内容插槽失效的问题。
## 1.1.12025-09-03
- 修复 动态dir目录不生效的问题
## 1.1.02025-09-02
- 新增 dir 属性,可以选择上传目录
## 1.0.132025-08-18
- 修复 删除文件后返回信息不包含file对象的问题
## 1.0.122025-04-14
- 修复 支付宝小程序 上传样式问题
## 1.0.102024-07-09
- 优化 vue3兼容性
## 1.0.92024-07-09
- 修复 value 属性不兼容vue3的bug
## 1.0.82024-03-20
- 补充 删除文件时返回文件下标
## 1.0.72024-02-21
- 新增 微信小程序选择视频时改用chooseMedia,并返回视频缩略图
## 1.0.62024-01-06
- 新增 微信小程序不再调用chooseImage,而是调用chooseMedia
## 1.0.52024-01-03
- 新增 上传文件至云存储携带本地文件名称
## 1.0.42023-03-29
- 修复 手动上传删除一个文件后不能再上传的bug
## 1.0.32022-12-19
- 新增 sourceType 属性, 可以自定义图片和视频选择的来源
## 1.0.22022-07-04
- 修复 在uni-forms下样式不生效的bug
## 1.0.12021-11-23
- 修复 参数为对象的情况下url在某些情况显示错误的bug
## 1.0.02021-11-19
- 优化 组件UI并提供设计资源详见:[https://uniapp.dcloud.io/component/uniui/resource](https://uniapp.dcloud.io/component/uniui/resource)
- 文档迁移,详见:[https://uniapp.dcloud.io/component/uniui/uni-file-picker](https://uniapp.dcloud.io/component/uniui/uni-file-picker)
## 0.2.162021-11-08
- 修复 传入空对象 显示错误的Bug
## 0.2.152021-08-30
- 修复 return-type="object" 时且存在v-model时无法删除文件的Bug
## 0.2.142021-08-23
- 新增 参数中返回 fileID 字段
## 0.2.132021-08-23
- 修复 腾讯云传入fileID 不能回显的bug
- 修复 选择图片后,不能放大的问题
## 0.2.122021-08-17
- 修复 由于 0.2.11 版本引起的不能回显图片的Bug
## 0.2.112021-08-16
- 新增 clearFiles(index) 方法,可以手动删除指定文件
- 修复 v-model 值设为 null 报错的Bug
## 0.2.102021-08-13
- 修复 return-type="object" 时无法删除文件的Bug
## 0.2.92021-08-03
- 修复 auto-upload 属性失效的Bug
## 0.2.82021-07-31
- 修复 fileExtname属性不指定值报错的Bug
## 0.2.72021-07-31
- 修复 在某种场景下图片不回显的Bug
## 0.2.62021-07-30
- 修复 return-type为object下返回值不正确的Bug
## 0.2.52021-07-30
- 修复(重要) H5 平台下如果和uni-forms组件一同使用导致页面卡死的问题
## 0.2.32021-07-28
- 优化 调整示例代码
## 0.2.22021-07-27
- 修复 vue3 下赋值错误的Bug
- 优化 h5平台下上传文件导致页面卡死的问题
## 0.2.02021-07-13
- 组件兼容 vue3如何创建vue3项目详见 [uni-app 项目支持 vue3 介绍](https://ask.dcloud.net.cn/article/37834)
## 0.1.12021-07-02
- 修复 sourceType 缺少默认值导致 ios 无法选择文件
## 0.1.02021-06-30
- 优化 解耦与uniCloud的强绑定关系 如不绑定服务空间默认autoUpload为false且不可更改
## 0.0.112021-06-30
- 修复 由 0.0.10 版本引发的 returnType 属性失效的问题
## 0.0.102021-06-29
- 优化 文件上传后进度条消失时机
## 0.0.92021-06-29
- 修复 在uni-forms 中,删除文件 获取的值不对的Bug
## 0.0.82021-06-15
- 修复 删除文件时无法触发 v-model 的Bug
## 0.0.72021-05-12
- 新增 组件示例地址
## 0.0.62021-04-09
- 修复 选择的文件非 file-extname 字段指定的扩展名报错的Bug
## 0.0.52021-04-09
- 优化 更新组件示例
## 0.0.42021-04-09
- 优化 file-extname 字段支持字符串写法,多个扩展名需要用逗号分隔
## 0.0.32021-02-05
- 调整为uni_modules目录规范
- 修复 微信小程序不指定 fileExtname 属性选择失败的Bug

View File

@@ -0,0 +1,287 @@
'use strict';
const ERR_MSG_OK = 'chooseAndUploadFile:ok';
const ERR_MSG_FAIL = 'chooseAndUploadFile:fail';
function chooseImage(opts) {
const {
count,
sizeType = ['original', 'compressed'],
sourceType,
extension
} = opts
return new Promise((resolve, reject) => {
// 微信由于旧接口不再维护针对微信小程序平台改用chooseMedia接口
// #ifdef MP-WEIXIN
uni.chooseMedia({
count,
sizeType,
sourceType,
mediaType: ['image'],
extension,
success(res) {
res.tempFiles.forEach(item => {
item.path = item.tempFilePath;
})
resolve(normalizeChooseAndUploadFileRes(res, 'image'));
},
fail(res) {
reject({
errMsg: res.errMsg.replace('chooseImage:fail', ERR_MSG_FAIL),
});
},
})
// #endif
// #ifndef MP-WEIXIN
uni.chooseImage({
count,
sizeType,
sourceType,
extension,
success(res) {
resolve(normalizeChooseAndUploadFileRes(res, 'image'));
},
fail(res) {
reject({
errMsg: res.errMsg.replace('chooseImage:fail', ERR_MSG_FAIL),
});
},
});
// #endif
});
}
function chooseVideo(opts) {
const {
count,
camera,
compressed,
maxDuration,
sourceType,
extension
} = opts;
return new Promise((resolve, reject) => {
// 微信由于旧接口不再维护针对微信小程序平台改用chooseMedia接口
// #ifdef MP-WEIXIN
uni.chooseMedia({
count,
compressed,
maxDuration,
sourceType,
extension,
mediaType: ['video'],
success(res) {
const {
tempFiles,
} = res;
resolve(normalizeChooseAndUploadFileRes({
errMsg: 'chooseVideo:ok',
tempFiles: tempFiles.map(item => {
return {
name: item.name || '',
path: item.tempFilePath,
thumbTempFilePath: item.thumbTempFilePath,
size:item.size,
type: (res.tempFile && res.tempFile.type) || '',
width:item.width,
height:item.height,
duration:item.duration,
fileType: 'video',
cloudPath: '',
}
}),
}, 'video'));
},
fail(res) {
reject({
errMsg: res.errMsg.replace('chooseVideo:fail', ERR_MSG_FAIL),
});
},
})
// #endif
// #ifndef MP-WEIXIN
uni.chooseVideo({
camera,
compressed,
maxDuration,
sourceType,
extension,
success(res) {
const {
tempFilePath,
duration,
size,
height,
width
} = res;
resolve(normalizeChooseAndUploadFileRes({
errMsg: 'chooseVideo:ok',
tempFilePaths: [tempFilePath],
tempFiles: [{
name: (res.tempFile && res.tempFile.name) || '',
path: tempFilePath,
size,
type: (res.tempFile && res.tempFile.type) || '',
width,
height,
duration,
fileType: 'video',
cloudPath: '',
}, ],
}, 'video'));
},
fail(res) {
reject({
errMsg: res.errMsg.replace('chooseVideo:fail', ERR_MSG_FAIL),
});
},
});
// #endif
});
}
function chooseAll(opts) {
const {
count,
extension
} = opts;
return new Promise((resolve, reject) => {
let chooseFile = uni.chooseFile;
if (typeof wx !== 'undefined' &&
typeof wx.chooseMessageFile === 'function') {
chooseFile = wx.chooseMessageFile;
}
if (typeof chooseFile !== 'function') {
return reject({
errMsg: ERR_MSG_FAIL + ' 请指定 type 类型,该平台仅支持选择 image 或 video。',
});
}
chooseFile({
type: 'all',
count,
extension,
success(res) {
resolve(normalizeChooseAndUploadFileRes(res));
},
fail(res) {
reject({
errMsg: res.errMsg.replace('chooseFile:fail', ERR_MSG_FAIL),
});
},
});
});
}
function normalizeChooseAndUploadFileRes(res, fileType) {
res.tempFiles.forEach((item, index) => {
if (!item.name) {
item.name = item.path.substring(item.path.lastIndexOf('/') + 1);
}
if (fileType) {
item.fileType = fileType;
}
item.cloudPath =
Date.now() + '_' + index + item.name.substring(item.name.lastIndexOf('.'));
});
if (!res.tempFilePaths) {
res.tempFilePaths = res.tempFiles.map((file) => file.path);
}
return res;
}
function uploadCloudFiles(files, max = 5, onUploadProgress) {
files = JSON.parse(JSON.stringify(files))
const len = files.length
let count = 0
let self = this
return new Promise(resolve => {
while (count < max) {
next()
}
function next() {
let cur = count++
if (cur >= len) {
!files.find(item => !item.url && !item.errMsg) && resolve(files)
return
}
const fileItem = files[cur]
const index = self.files.findIndex(v => v.uuid === fileItem.uuid)
fileItem.url = ''
delete fileItem.errMsg
uniCloud
.uploadFile({
filePath: fileItem.path,
cloudPath: fileItem.cloudPath,
fileType: fileItem.fileType,
onUploadProgress: res => {
res.index = index
onUploadProgress && onUploadProgress(res)
}
})
.then(res => {
fileItem.url = res.fileID
fileItem.index = index
if (cur < len) {
next()
}
})
.catch(res => {
fileItem.errMsg = res.errMsg || res.message
fileItem.index = index
if (cur < len) {
next()
}
})
}
})
}
function uploadFiles(choosePromise, {
onChooseFile,
onUploadProgress
}) {
return choosePromise
.then((res) => {
if (onChooseFile) {
const customChooseRes = onChooseFile(res);
if (typeof customChooseRes !== 'undefined') {
return Promise.resolve(customChooseRes).then((chooseRes) => typeof chooseRes === 'undefined' ?
res : chooseRes);
}
}
return res;
})
.then((res) => {
if (res === false) {
return {
errMsg: ERR_MSG_OK,
tempFilePaths: [],
tempFiles: [],
};
}
return res
})
}
function chooseAndUploadFile(opts = {
type: 'all'
}) {
if (opts.type === 'image') {
return uploadFiles(chooseImage(opts), opts);
} else if (opts.type === 'video') {
return uploadFiles(chooseVideo(opts), opts);
}
return uploadFiles(chooseAll(opts), opts);
}
export {
chooseAndUploadFile,
uploadCloudFiles
};

View File

@@ -0,0 +1,680 @@
<template>
<view class="uni-file-picker">
<view v-if="title" class="uni-file-picker__header">
<text class="file-title">{{ title }}</text>
<text class="file-count">{{ filesList.length }}/{{ limitLength }}</text>
</view>
<upload-image v-if="fileMediatype === 'image' && showType === 'grid'" :readonly="readonly" :image-styles="imageStyles" :files-list="filesList" :limit="limitLength" :disablePreview="disablePreview" :delIcon="delIcon" @uploadFiles="uploadFiles" @choose="choose" @delFile="delFile">
<slot>
<view class="icon-add"></view>
<view class="icon-add rotate"></view>
</slot>
</upload-image>
<upload-file v-if="fileMediatype !== 'image' || showType !== 'grid'" :readonly="readonly" :list-styles="listStyles" :files-list="filesList" :showType="showType" :delIcon="delIcon" @uploadFiles="uploadFiles" @choose="choose" @delFile="delFile">
<slot><button type="primary" size="mini">选择文件</button></slot>
</upload-file>
</view>
</template>
<script>
import {
chooseAndUploadFile,
uploadCloudFiles
} from './choose-and-upload-file.js'
import {
get_file_ext,
get_extname,
get_files_and_is_max,
get_file_info,
get_file_data
} from './utils.js'
import uploadImage from './upload-image.vue'
import uploadFile from './upload-file.vue'
let fileInput = null
/**
* FilePicker 文件选择上传
* @description 文件选择上传组件,可以选择图片、视频等任意文件并上传到当前绑定的服务空间
* @tutorial https://ext.dcloud.net.cn/plugin?id=4079
* @property {Object|Array} value 组件数据,通常用来回显 ,类型由return-type属性决定
* @property {Boolean} disabled = [true|false] 组件禁用
* @value true 禁用
* @value false 取消禁用
* @property {Boolean} readonly = [true|false] 组件只读,不可选择,不显示进度,不显示删除按钮
* @value true 只读
* @value false 取消只读
* @property {String} return-type = [array|object] 限制 value 格式,当为 object 时 ,组件只能单选,且会覆盖
* @value array 规定 value 属性的类型为数组
* @value object 规定 value 属性的类型为对象
* @property {Boolean} disable-preview = [true|false] 禁用图片预览,仅 mode:grid 时生效
* @value true 禁用图片预览
* @value false 取消禁用图片预览
* @property {Boolean} del-icon = [true|false] 是否显示删除按钮
* @value true 显示删除按钮
* @value false 不显示删除按钮
* @property {Boolean} auto-upload = [true|false] 是否自动上传值为true则只触发@select,可自行上传
* @value true 自动上传
* @value false 取消自动上传
* @property {Number|String} limit 最大选择个数 h5 会自动忽略多选的部分
* @property {String} title 组件标题,右侧显示上传计数
* @property {String} mode = [list|grid] 选择文件后的文件列表样式
* @value list 列表显示
* @value grid 宫格显示
* @property {String} file-mediatype = [image|video|all] 选择文件类型
* @value image 只选择图片
* @value video 只选择视频
* @value all 选择所有文件
* @property {Array} file-extname 选择文件后缀,根据 file-mediatype 属性而不同
* @property {Object} list-style mode:list 时的样式
* @property {Object} image-styles 选择文件后缀,根据 file-mediatype 属性而不同
* @event {Function} select 选择文件后触发
* @event {Function} progress 文件上传时触发
* @event {Function} success 上传成功触发
* @event {Function} fail 上传失败触发
* @event {Function} delete 文件从列表移除时触发
*/
export default {
name: 'uniFilePicker',
components: {
uploadImage,
uploadFile
},
options: {
virtualHost: true
},
emits: ['select', 'success', 'fail', 'progress', 'delete', 'update:modelValue', 'input'],
props: {
modelValue: {
type: [Array, Object],
default () {
return []
}
},
value: {
type: [Array, Object],
default () {
return []
}
},
disabled: {
type: Boolean,
default: false
},
disablePreview: {
type: Boolean,
default: false
},
delIcon: {
type: Boolean,
default: true
},
// 自动上传
autoUpload: {
type: Boolean,
default: true
},
// 最大选择个数 h5只能限制单选或是多选
limit: {
type: [Number, String],
default: 9
},
// 列表样式 grid | list | list-card
mode: {
type: String,
default: 'grid'
},
// 选择文件类型 image/video/all
fileMediatype: {
type: String,
default: 'image'
},
// 文件类型筛选
fileExtname: {
type: [Array, String],
default () {
return []
}
},
title: {
type: String,
default: ''
},
listStyles: {
type: Object,
default () {
return {
// 是否显示边框
border: true,
// 是否显示分隔线
dividline: true,
// 线条样式
borderStyle: {}
}
}
},
imageStyles: {
type: Object,
default () {
return {
width: 'auto',
height: 'auto'
}
}
},
readonly: {
type: Boolean,
default: false
},
returnType: {
type: String,
default: 'array'
},
sizeType: {
type: Array,
default () {
return ['original', 'compressed']
}
},
sourceType: {
type: Array,
default () {
return ['album', 'camera']
}
},
provider: {
type: String,
default: '' // 默认上传到 unicloud 内置存储 extStorage 扩展存储
},
dir: {
type: String,
default: ''
}
},
data() {
return {
files: [],
localValue: [],
dirPath: ''
}
},
watch: {
value: {
handler(newVal, oldVal) {
this.setValue(newVal, oldVal)
},
immediate: true
},
modelValue: {
handler(newVal, oldVal) {
this.setValue(newVal, oldVal)
},
immediate: true
},
dir: {
handler(newVal) {
this.dirPath = newVal
},
immediate: true
},
},
computed: {
filesList() {
let files = []
this.files.forEach(v => {
files.push(v)
})
return files
},
showType() {
if (this.fileMediatype === 'image') {
return this.mode
}
return 'list'
},
limitLength() {
if (this.returnType === 'object') {
return 1
}
if (!this.limit) {
return 1
}
if (this.limit >= 9) {
return 9
}
return this.limit
}
},
created() {
// TODO 兼容不开通服务空间的情况
if (!(uniCloud.config && uniCloud.config.provider)) {
this.noSpace = true
uniCloud.chooseAndUploadFile = chooseAndUploadFile
}
this.form = this.getForm('uniForms')
this.formItem = this.getForm('uniFormsItem')
if (this.form && this.formItem) {
if (this.formItem.name) {
this.rename = this.formItem.name
this.form.inputChildrens.push(this)
}
}
},
methods: {
/**
* 公开用户使用,清空文件
* @param {Object} index
*/
clearFiles(index) {
if (index !== 0 && !index) {
this.files = []
this.$nextTick(() => {
this.setEmit()
})
} else {
this.files.splice(index, 1)
}
this.$nextTick(() => {
this.setEmit()
})
},
/**
* 公开用户使用,继续上传
*/
upload() {
let files = []
this.files.forEach((v, index) => {
if (v.status === 'ready' || v.status === 'error') {
files.push(Object.assign({}, v))
}
})
return this.uploadFiles(files)
},
async setValue(newVal, oldVal) {
const newData = async (v) => {
const reg = /cloud:\/\/([\w.]+\/?)\S*/
let url = ''
if (v.fileID) {
url = v.fileID
} else {
url = v.url
}
if (reg.test(url)) {
v.fileID = url
v.url = await this.getTempFileURL(url)
}
if (v.url) v.path = v.url
return v
}
if (this.returnType === 'object') {
if (newVal) {
await newData(newVal)
} else {
newVal = {}
}
} else {
if (!newVal) newVal = []
for (let i = 0; i < newVal.length; i++) {
let v = newVal[i]
await newData(v)
}
}
this.localValue = newVal
if (this.form && this.formItem && !this.is_reset) {
this.is_reset = false
this.formItem.setValue(this.localValue)
}
let filesData = Object.keys(newVal).length > 0 ? newVal : [];
this.files = [].concat(filesData)
},
/**
* 选择文件
*/
choose() {
if (this.disabled) return
if (this.files.length >= Number(this.limitLength) && this.showType !== 'grid' && this.returnType ===
'array') {
uni.showToast({
title: `您最多选择 ${this.limitLength} 个文件`,
icon: 'none'
})
return
}
this.chooseFiles()
},
/**
* 选择文件并上传
*/
chooseFiles() {
const _extname = get_extname(this.fileExtname)
// 获取后缀
uniCloud
.chooseAndUploadFile({
type: this.fileMediatype,
compressed: false,
sizeType: this.sizeType,
sourceType: this.sourceType,
// TODO 如果为空video 有问题
extension: _extname.length > 0 ? _extname : undefined,
count: this.limitLength - this.files.length, //默认9
onChooseFile: this.chooseFileCallback,
onUploadProgress: progressEvent => {
this.setProgress(progressEvent, progressEvent.index)
}
})
.then(result => {
this.setSuccessAndError(result.tempFiles)
})
.catch(err => {
console.log('选择失败', err)
})
},
/**
* 选择文件回调
* @param {Object} res
*/
async chooseFileCallback(res) {
const _extname = get_extname(this.fileExtname)
const is_one = (Number(this.limitLength) === 1 &&
this.disablePreview &&
!this.disabled) ||
this.returnType === 'object'
// 如果这有一个文件 ,需要清空本地缓存数据
if (is_one) {
this.files = []
}
let {
filePaths,
files
} = get_files_and_is_max(res, _extname)
if (!(_extname && _extname.length > 0)) {
filePaths = res.tempFilePaths
files = res.tempFiles
}
let currentData = []
for (let i = 0; i < files.length; i++) {
if (this.limitLength - this.files.length <= 0) break
files[i].uuid = Date.now()
let filedata = await get_file_data(files[i], this.fileMediatype)
filedata.progress = 0
filedata.status = 'ready'
// fix by mehaotian ,统一返回删除也包含file对象
let fileTempData = {
...filedata,
file: files[i]
}
this.files.push(fileTempData)
currentData.push(fileTempData)
}
this.$emit('select', {
tempFiles: currentData,
tempFilePaths: filePaths
})
res.tempFiles = files
// 停止自动上传
if (!this.autoUpload || this.noSpace) {
res.tempFiles = []
}
res.tempFiles.map((fileItem, index) => {
this.provider && (fileItem.provider = this.provider);
const fileNameSplit = fileItem.name.split('.')
const ext = fileNameSplit.pop()
const fileName = fileNameSplit.join('.').replace(/[\s\/\?<>\\:\*\|":]/g, '_')
// 选择文件目录上传
let dir = this.dirPath || ''; // 防止用户传入的 dir 不正常
// 检查最后一个字符是否为 '/'(同时处理空字符串情况)
if (dir && dir[dir.length - 1] !== '/') {
dir += '/';
}
fileItem.cloudPath = dir + fileName + '_' + Date.now() + '_' + index + '.' + ext
fileItem.cloudPathAsRealPath = true
return fileItem
})
return res
},
/**
* 批传
* @param {Object} e
*/
uploadFiles(files) {
files = [].concat(files)
return uploadCloudFiles.call(this, files, 5, res => {
this.setProgress(res, res.index, true)
})
.then(result => {
this.setSuccessAndError(result)
return result;
})
.catch(err => {
console.log(err)
})
},
/**
* 成功或失败
*/
async setSuccessAndError(res, fn) {
let successData = []
let errorData = []
let tempFilePath = []
let errorTempFilePath = []
for (let i = 0; i < res.length; i++) {
const item = res[i]
const index = item.uuid ? this.files.findIndex(p => p.uuid === item.uuid) : item.index
if (index === -1 || !this.files) break
if (item.errMsg === 'request:fail') {
this.files[index].url = item.path
this.files[index].status = 'error'
this.files[index].errMsg = item.errMsg
// this.files[index].progress = -1
errorData.push(this.files[index])
errorTempFilePath.push(this.files[index].url)
} else {
this.files[index].errMsg = ''
this.files[index].fileID = item.url
const reg = /cloud:\/\/([\w.]+\/?)\S*/
if (reg.test(item.url)) {
this.files[index].url = await this.getTempFileURL(item.url)
} else {
this.files[index].url = item.url
}
this.files[index].status = 'success'
this.files[index].progress += 1
successData.push(this.files[index])
tempFilePath.push(this.files[index].fileID)
}
}
if (successData.length > 0) {
this.setEmit()
// 状态改变返回
this.$emit('success', {
tempFiles: this.backObject(successData),
tempFilePaths: tempFilePath
})
}
if (errorData.length > 0) {
this.$emit('fail', {
tempFiles: this.backObject(errorData),
tempFilePaths: errorTempFilePath
})
}
},
/**
* 获取进度
* @param {Object} progressEvent
* @param {Object} index
* @param {Object} type
*/
setProgress(progressEvent, index, type) {
const fileLenth = this.files.length
const percentNum = (index / fileLenth) * 100
const percentCompleted = Math.round((progressEvent.loaded * 100) / progressEvent.total)
let idx = index
if (!type) {
idx = this.files.findIndex(p => p.uuid === progressEvent.tempFile.uuid)
}
if (idx === -1 || !this.files[idx]) return
// fix by mehaotian 100 就会消失,-1 是为了让进度条消失
this.files[idx].progress = percentCompleted - 1
// 上传中
this.$emit('progress', {
index: idx,
progress: parseInt(percentCompleted),
tempFile: this.files[idx]
})
},
/**
* 删除文件
* @param {Object} index
*/
delFile(index) {
this.$emit('delete', {
index,
tempFile: this.files[index],
tempFilePath: this.files[index].url
})
this.files.splice(index, 1)
this.$nextTick(() => {
this.setEmit()
})
},
/**
* 获取文件名和后缀
* @param {Object} name
*/
getFileExt(name) {
const last_len = name.lastIndexOf('.')
const len = name.length
return {
name: name.substring(0, last_len),
ext: name.substring(last_len + 1, len)
}
},
/**
* 处理返回事件
*/
setEmit() {
let data = []
if (this.returnType === 'object') {
data = this.backObject(this.files)[0]
this.localValue = data ? data : null
} else {
data = this.backObject(this.files)
if (!this.localValue) {
this.localValue = []
}
this.localValue = [...data]
}
// #ifdef VUE3
this.$emit('update:modelValue', this.localValue)
// #endif
// #ifndef VUE3
this.$emit('input', this.localValue)
// #endif
},
/**
* 处理返回参数
* @param {Object} files
*/
backObject(files) {
let newFilesData = []
files.forEach(v => {
newFilesData.push({
extname: v.extname,
fileType: v.fileType,
image: v.image,
name: v.name,
path: v.path,
size: v.size,
fileID: v.fileID,
url: v.url,
// 修改删除一个文件后不能再上传的bug, #694
uuid: v.uuid,
status: v.status,
cloudPath: v.cloudPath
})
})
return newFilesData
},
async getTempFileURL(fileList) {
fileList = {
fileList: [].concat(fileList)
}
const urls = await uniCloud.getTempFileURL(fileList)
return urls.fileList[0].tempFileURL || ''
},
/**
* 获取父元素实例
*/
getForm(name = 'uniForms') {
let parent = this.$parent;
let parentName = parent.$options.name;
while (parentName !== name) {
parent = parent.$parent;
if (!parent) return false;
parentName = parent.$options.name;
}
return parent;
}
}
}
</script>
<style>
.uni-file-picker {
/* #ifndef APP-NVUE */
box-sizing: border-box;
overflow: hidden;
width: 100%;
/* #endif */
flex: 1;
}
.uni-file-picker__header {
padding-top: 5px;
padding-bottom: 10px;
/* #ifndef APP-NVUE */
display: flex;
/* #endif */
justify-content: space-between;
}
.file-title {
font-size: 14px;
color: #333;
}
.file-count {
font-size: 14px;
color: #999;
}
.icon-add {
width: 50px;
height: 5px;
background-color: #f1f1f1;
border-radius: 2px;
}
.rotate {
position: absolute;
transform: rotate(90deg);
}
</style>

View File

@@ -0,0 +1,323 @@
<template>
<view class="uni-file-picker__files">
<view v-if="!readonly" class="files-button" @click="choose">
<slot></slot>
</view>
<!-- :class="{'is-text-box':showType === 'list'}" -->
<view v-if="list.length > 0" class="uni-file-picker__lists is-text-box" :style="borderStyle">
<!-- ,'is-list-card':showType === 'list-card' -->
<view class="uni-file-picker__lists-box" v-for="(item ,index) in list" :key="index" :class="{
'files-border':index !== 0 && styles.dividline}" :style="index !== 0 && styles.dividline &&borderLineStyle">
<view class="uni-file-picker__item">
<!-- :class="{'is-text-image':showType === 'list'}" -->
<!-- <view class="files__image is-text-image">
<image class="header-image" :src="item.logo" mode="aspectFit"></image>
</view> -->
<view class="files__name">{{item.name}}</view>
<view v-if="delIcon&&!readonly" class="icon-del-box icon-files" @click="delFile(index)">
<view class="icon-del icon-files"></view>
<view class="icon-del rotate"></view>
</view>
</view>
<view v-if="(item.progress && item.progress !== 100) ||item.progress===0 " class="file-picker__progress">
<progress class="file-picker__progress-item" :percent="item.progress === -1?0:item.progress" stroke-width="4" :backgroundColor="item.errMsg?'#ff5a5f':'#EBEBEB'" />
</view>
<view v-if="item.status === 'error'" class="file-picker__mask" @click.stop="uploadFiles(item,index)">
点击重试
</view>
</view>
</view>
</view>
</template>
<script>
export default {
name: "uploadFile",
emits: ['uploadFiles', 'choose', 'delFile'],
props: {
filesList: {
type: Array,
default () {
return []
}
},
delIcon: {
type: Boolean,
default: true
},
limit: {
type: [Number, String],
default: 9
},
showType: {
type: String,
default: ''
},
listStyles: {
type: Object,
default () {
return {
// 是否显示边框
border: true,
// 是否显示分隔线
dividline: true,
// 线条样式
borderStyle: {}
}
}
},
readonly: {
type: Boolean,
default: false
}
},
computed: {
list() {
let files = []
this.filesList.forEach(v => {
files.push(v)
})
return files
},
styles() {
let styles = {
border: true,
dividline: true,
'border-style': {}
}
return Object.assign(styles, this.listStyles)
},
borderStyle() {
let {
borderStyle,
border
} = this.styles
let obj = {}
if (!border) {
obj.border = 'none'
} else {
let width = (borderStyle && borderStyle.width) || 1
width = this.value2px(width)
let radius = (borderStyle && borderStyle.radius) || 5
radius = this.value2px(radius)
obj = {
'border-width': width,
'border-style': (borderStyle && borderStyle.style) || 'solid',
'border-color': (borderStyle && borderStyle.color) || '#eee',
'border-radius': radius
}
}
let classles = ''
for (let i in obj) {
classles += `${i}:${obj[i]};`
}
return classles
},
borderLineStyle() {
let obj = {}
let {
borderStyle
} = this.styles
if (borderStyle && borderStyle.color) {
obj['border-color'] = borderStyle.color
}
if (borderStyle && borderStyle.width) {
let width = borderStyle && borderStyle.width || 1
let style = borderStyle && borderStyle.style || 0
if (typeof width === 'number') {
width += 'px'
} else {
width = width.indexOf('px') ? width : width + 'px'
}
obj['border-width'] = width
if (typeof style === 'number') {
style += 'px'
} else {
style = style.indexOf('px') ? style : style + 'px'
}
obj['border-top-style'] = style
}
let classles = ''
for (let i in obj) {
classles += `${i}:${obj[i]};`
}
return classles
}
},
methods: {
uploadFiles(item, index) {
this.$emit("uploadFiles", {
item,
index
})
},
choose() {
this.$emit("choose")
},
delFile(index) {
this.$emit('delFile', index)
},
value2px(value) {
if (typeof value === 'number') {
value += 'px'
} else {
value = value.indexOf('px') !== -1 ? value : value + 'px'
}
return value
}
}
}
</script>
<style lang="scss">
.uni-file-picker__files {
/* #ifndef APP-NVUE */
display: flex;
/* #endif */
flex-direction: column;
justify-content: flex-start;
}
.files-button {
// border: 1px red solid;
}
.uni-file-picker__lists {
position: relative;
margin-top: 5px;
overflow: hidden;
}
.file-picker__mask {
/* #ifndef APP-NVUE */
display: flex;
/* #endif */
justify-content: center;
align-items: center;
position: absolute;
right: 0;
top: 0;
bottom: 0;
left: 0;
color: #fff;
font-size: 14px;
background-color: rgba(0, 0, 0, 0.4);
}
.uni-file-picker__lists-box {
position: relative;
}
.uni-file-picker__item {
/* #ifndef APP-NVUE */
display: flex;
/* #endif */
align-items: center;
padding: 8px 10px;
padding-right: 5px;
padding-left: 10px;
}
.files-border {
border-top: 1px #eee solid;
}
.files__name {
flex: 1;
font-size: 14px;
color: #666;
margin-right: 25px;
/* #ifndef APP-NVUE */
word-break: break-all;
word-wrap: break-word;
/* #endif */
}
.icon-files {
/* #ifndef APP-NVUE */
position: static;
background-color: initial;
/* #endif */
}
// .icon-files .icon-del {
// background-color: #333;
// width: 12px;
// height: 1px;
// }
.is-list-card {
border: 1px #eee solid;
margin-bottom: 5px;
border-radius: 5px;
box-shadow: 0 0 2px 0px rgba(0, 0, 0, 0.1);
padding: 5px;
}
.files__image {
width: 40px;
height: 40px;
margin-right: 10px;
}
.header-image {
width: 100%;
height: 100%;
}
.is-text-box {
border: 1px #eee solid;
border-radius: 5px;
}
.is-text-image {
width: 25px;
height: 25px;
margin-left: 5px;
}
.rotate {
position: absolute;
transform: rotate(90deg);
}
.icon-del-box {
/* #ifndef APP-NVUE */
display: flex;
margin: auto 0;
/* #endif */
align-items: center;
justify-content: center;
position: absolute;
top: 0px;
bottom: 0;
right: 5px;
height: 26px;
width: 26px;
// border-radius: 50%;
// background-color: rgba(0, 0, 0, 0.5);
z-index: 2;
transform: rotate(-45deg);
}
.icon-del {
width: 15px;
height: 1px;
background-color: #333;
// border-radius: 1px;
}
/* #ifdef H5 */
@media all and (min-width: 768px) {
.uni-file-picker__files {
max-width: 375px;
}
}
/* #endif */
</style>

View File

@@ -0,0 +1,285 @@
<template>
<view class="uni-file-picker__container">
<view class="file-picker__box" v-for="(item,index) in filesList" :key="index" :style="boxStyle">
<view class="file-picker__box-content" :style="borderStyle">
<image class="file-image" :src="item.url" mode="aspectFill" @click.stop="prviewImage(item,index)"></image>
<view v-if="delIcon && !readonly" class="icon-del-box" @click.stop="delFile(index)">
<view class="icon-del"></view>
<view class="icon-del rotate"></view>
</view>
<view v-if="(item.progress && item.progress !== 100) ||item.progress===0 " class="file-picker__progress">
<progress class="file-picker__progress-item" :percent="item.progress === -1?0:item.progress" stroke-width="4"
:backgroundColor="item.errMsg?'#ff5a5f':'#EBEBEB'" />
</view>
<view v-if="item.errMsg" class="file-picker__mask" @click.stop="uploadFiles(item,index)">
点击重试
</view>
</view>
</view>
<view v-if="filesList.length < limit" class="file-picker__box" :style="boxStyle">
<view class="file-picker__box-content is-add" :style="borderStyle" @click="choose">
<slot></slot>
</view>
</view>
</view>
</template>
<script>
export default {
name: "uploadImage",
emits:['uploadFiles','choose','delFile'],
props: {
filesList: {
type: Array,
default () {
return []
}
},
disabled:{
type: Boolean,
default: false
},
disablePreview: {
type: Boolean,
default: false
},
limit: {
type: [Number, String],
default: 9
},
imageStyles: {
type: Object,
default () {
return {
width: 'auto',
height: 'auto',
border: {}
}
}
},
delIcon: {
type: Boolean,
default: true
},
readonly:{
type:Boolean,
default:false
}
},
computed: {
styles() {
let styles = {
width: 'auto',
height: 'auto',
border: {}
}
return Object.assign(styles, this.imageStyles)
},
boxStyle() {
const {
width = 'auto',
height = 'auto'
} = this.styles
let obj = {}
if (height === 'auto') {
if (width !== 'auto') {
obj.height = this.value2px(width)
obj['padding-top'] = 0
} else {
obj.height = 0
}
} else {
obj.height = this.value2px(height)
obj['padding-top'] = 0
}
if (width === 'auto') {
if (height !== 'auto') {
obj.width = this.value2px(height)
} else {
obj.width = '33.3%'
}
} else {
obj.width = this.value2px(width)
}
let classles = ''
for(let i in obj){
classles+= `${i}:${obj[i]};`
}
return classles
},
borderStyle() {
let {
border
} = this.styles
let obj = {}
const widthDefaultValue = 1
const radiusDefaultValue = 3
if (typeof border === 'boolean') {
obj.border = border ? '1px #eee solid' : 'none'
} else {
let width = (border && border.width) || widthDefaultValue
width = this.value2px(width)
let radius = (border && border.radius) || radiusDefaultValue
radius = this.value2px(radius)
obj = {
'border-width': width,
'border-style': (border && border.style) || 'solid',
'border-color': (border && border.color) || '#eee',
'border-radius': radius
}
}
let classles = ''
for(let i in obj){
classles+= `${i}:${obj[i]};`
}
return classles
}
},
methods: {
uploadFiles(item, index) {
this.$emit("uploadFiles", item)
},
choose() {
if(this.readonly) return
this.$emit("choose")
},
delFile(index) {
if(this.readonly) return
this.$emit('delFile', index)
},
prviewImage(img, index) {
if(this.readonly) return
let urls = []
if(Number(this.limit) === 1&&this.disablePreview&&!this.disabled){
this.$emit("choose")
}
if(this.disablePreview) return
this.filesList.forEach(i => {
urls.push(i.url)
})
uni.previewImage({
urls: urls,
current: index
});
},
value2px(value) {
if (typeof value === 'number') {
value += 'px'
} else {
if (value.indexOf('%') === -1) {
value = value.indexOf('px') !== -1 ? value : value + 'px'
}
}
return value
}
}
}
</script>
<style lang="scss">
.uni-file-picker__container {
/* #ifndef APP-NVUE */
display: flex;
box-sizing: border-box;
/* #endif */
flex-wrap: wrap;
margin: -5px;
}
.file-picker__box {
position: relative;
// flex: 0 0 33.3%;
width: 33.3%;
height: 0;
padding-top: 33.33%;
/* #ifndef APP-NVUE */
box-sizing: border-box;
/* #endif */
}
.file-picker__box-content {
position: absolute;
top: 0;
right: 0;
bottom: 0;
left: 0;
margin: 5px;
border: 1px #eee solid;
border-radius: 5px;
overflow: hidden;
}
.file-picker__progress {
position: absolute;
bottom: 0;
left: 0;
right: 0;
/* border: 1px red solid; */
z-index: 2;
}
.file-picker__progress-item {
width: 100%;
}
.file-picker__mask {
/* #ifndef APP-NVUE */
display: flex;
/* #endif */
justify-content: center;
align-items: center;
position: absolute;
right: 0;
top: 0;
bottom: 0;
left: 0;
color: #fff;
font-size: 12px;
background-color: rgba(0, 0, 0, 0.4);
}
.file-image {
width: 100%;
height: 100%;
}
.is-add {
/* #ifndef APP-NVUE */
display: flex;
/* #endif */
align-items: center;
justify-content: center;
}
.rotate {
position: absolute;
transform: rotate(90deg);
}
.icon-del-box {
/* #ifndef APP-NVUE */
display: flex;
/* #endif */
align-items: center;
justify-content: center;
position: absolute;
top: 3px;
right: 3px;
height: 26px;
width: 26px;
border-radius: 50%;
background-color: rgba(0, 0, 0, 0.5);
z-index: 2;
transform: rotate(-45deg);
}
.icon-del {
width: 15px;
height: 2px;
background-color: #fff;
border-radius: 2px;
}
</style>

View File

@@ -0,0 +1,110 @@
/**
* 获取文件名和后缀
* @param {String} name
*/
export const get_file_ext = (name) => {
const last_len = name.lastIndexOf('.')
const len = name.length
return {
name: name.substring(0, last_len),
ext: name.substring(last_len + 1, len)
}
}
/**
* 获取扩展名
* @param {Array} fileExtname
*/
export const get_extname = (fileExtname) => {
if (!Array.isArray(fileExtname)) {
let extname = fileExtname.replace(/(\[|\])/g, '')
return extname.split(',')
} else {
return fileExtname
}
return []
}
/**
* 获取文件和检测是否可选
*/
export const get_files_and_is_max = (res, _extname) => {
let filePaths = []
let files = []
if(!_extname || _extname.length === 0){
return {
filePaths,
files
}
}
res.tempFiles.forEach(v => {
let fileFullName = get_file_ext(v.name)
const extname = fileFullName.ext.toLowerCase()
if (_extname.indexOf(extname) !== -1) {
files.push(v)
filePaths.push(v.path)
}
})
if (files.length !== res.tempFiles.length) {
uni.showToast({
title: `当前选择了${res.tempFiles.length}个文件 ${res.tempFiles.length - files.length} 个文件格式不正确`,
icon: 'none',
duration: 5000
})
}
return {
filePaths,
files
}
}
/**
* 获取图片信息
* @param {Object} filepath
*/
export const get_file_info = (filepath) => {
return new Promise((resolve, reject) => {
uni.getImageInfo({
src: filepath,
success(res) {
resolve(res)
},
fail(err) {
reject(err)
}
})
})
}
/**
* 获取封装数据
*/
export const get_file_data = async (files, type = 'image') => {
// 最终需要上传数据库的数据
let fileFullName = get_file_ext(files.name)
const extname = fileFullName.ext.toLowerCase()
let filedata = {
name: files.name,
uuid: files.uuid,
extname: extname || '',
cloudPath: files.cloudPath,
fileType: files.fileType,
thumbTempFilePath: files.thumbTempFilePath,
url: files.path || files.path,
size: files.size, //单位是字节
image: {},
path: files.path,
video: {}
}
if (type === 'image') {
const imageinfo = await get_file_info(files.path)
delete filedata.video
filedata.image.width = imageinfo.width
filedata.image.height = imageinfo.height
filedata.image.location = imageinfo.path
} else {
delete filedata.image
}
return filedata
}

View File

@@ -0,0 +1,105 @@
{
"id": "uni-file-picker",
"displayName": "uni-file-picker 文件选择上传",
"version": "1.1.3",
"description": "文件选择上传组件,可以选择图片、视频等任意文件并上传到当前绑定的服务空间",
"keywords": [
"uni-ui",
"uniui",
"图片上传",
"文件上传"
],
"repository": "https://github.com/dcloudio/uni-ui",
"engines": {
"HBuilderX": "",
"uni-app": "^4.33",
"uni-app-x": ""
},
"directories": {
"example": "../../temps/example_temps"
},
"dcloudext": {
"sale": {
"regular": {
"price": "0.00"
},
"sourcecode": {
"price": "0.00"
}
},
"contact": {
"qq": ""
},
"declaration": {
"ads": "无",
"data": "无",
"permissions": "无"
},
"npmurl": "https://www.npmjs.com/package/@dcloudio/uni-ui",
"type": "component-vue",
"darkmode": "x",
"i18n": "x",
"widescreen": "x"
},
"uni_modules": {
"dependencies": [
"uni-scss"
],
"encrypt": [],
"platforms": {
"cloud": {
"tcb": "√",
"aliyun": "√",
"alipay": "√"
},
"client": {
"uni-app": {
"vue": {
"vue2": "√",
"vue3": "√"
},
"web": {
"safari": "√",
"chrome": "√"
},
"app": {
"vue": "√",
"nvue": "-",
"android": "√",
"ios": "√",
"harmony": "√"
},
"mp": {
"weixin": "√",
"alipay": "√",
"toutiao": "√",
"baidu": "√",
"kuaishou": "√",
"jd": "-",
"harmony": "-",
"qq": "√",
"lark": "-"
},
"quickapp": {
"huawei": "√",
"union": "√"
}
},
"uni-app-x": {
"web": {
"safari": "-",
"chrome": "-"
},
"app": {
"android": "-",
"ios": "-",
"harmony": "-"
},
"mp": {
"weixin": "-"
}
}
}
}
}
}

View File

@@ -0,0 +1,10 @@
## FilePicker 文件选择上传
> **组件名uni-file-picker**
> 代码块: `uFilePicker`
文件选择上传组件,可以选择图片、视频等任意文件并上传到当前绑定的服务空间
### [查看文档](https://uniapp.dcloud.io/component/uniui/uni-file-picker)

View File

@@ -1,56 +1,26 @@
/**
* FileValidator.js
* 封装好的文件安全校验类
*/
// ==========================================
// 1. 预定义:已知文件类型的魔数 (Signature Database)
// ==========================================
const KNOWN_SIGNATURES = {
// === 图片 ===
png: '89504E470D0A1A0A',
jpg: 'FFD8FF',
jpeg: 'FFD8FF',
gif: '47494638',
webp: '52494646', // RIFF Header
// === 文档 (Office 新版 - ZIP 格式) ===
webp: '52494646',
docx: '504B0304',
xlsx: '504B0304',
pptx: '504B0304',
// === 文档 (Office 旧版 - OLECF 格式) ===
doc: 'D0CF11E0',
xls: 'D0CF11E0',
ppt: 'D0CF11E0',
// === 其他 ===
pdf: '25504446',
// === 纯文本 (无固定魔数,需特殊算法检测) ===
txt: 'TYPE_TEXT',
csv: 'TYPE_TEXT',
md: 'TYPE_TEXT',
json: 'TYPE_TEXT',
};
// ==========================================
// 2. 核心类定义
// ==========================================
export class FileValidator {
/**
* 构造函数
* @param {Object} options 配置项
* @param {number} [options.maxSizeMB=10] 最大文件大小 (MB)
* @param {string[]} [options.allowedExtensions] 允许的扩展名列表 (如 ['jpg', 'png']),默认允许全部已知类型
*/
version = '1.0.0';
signs = Object.keys(KNOWN_SIGNATURES);
constructor(options = {}) {
// 配置大小 (默认 10MB)
this.maxSizeMB = options.maxSizeMB || 10;
// 配置允许的类型
// 如果传入了 allowedExtensions则只使用传入的否则使用全部 KNOWN_SIGNATURES
if (options.allowedExtensions && Array.isArray(options.allowedExtensions)) {
this.allowedConfig = {};
options.allowedExtensions.forEach((ext) => {
@@ -63,103 +33,122 @@ export class FileValidator {
});
} else {
this.allowedConfig = {
...KNOWN_SIGNATURES
...KNOWN_SIGNATURES,
};
}
}
/**
* 辅助ArrayBuffer 转 Hex 字符串
*/
_isValidUTF8(buffer) {
try {
const decoder = new TextDecoder('utf-8', {
fatal: true,
});
decoder.decode(buffer);
return true;
} catch (e) {
return false;
}
}
_bufferToHex(buffer) {
return Array.prototype.map
.call(new Uint8Array(buffer), (x) => ('00' + x.toString(16)).slice(-2))
.join('')
.toUpperCase();
}
/**
* 辅助:纯文本抽样检测
*/
_isCleanText(buffer) {
const bytes = new Uint8Array(buffer);
const checkLen = Math.min(bytes.length, 1000);
let suspiciousCount = 0;
for (let i = 0; i < checkLen; i++) {
const byte = bytes[i];
// 允许常见控制符: 9(Tab), 10(LF), 13(CR)
// 0-31 范围内其他的通常是二进制控制符
if (byte < 32 && ![9, 10, 13].includes(byte)) {
suspiciousCount++;
_countCSVRows(buffer) {
const decoder = new TextDecoder('utf-8');
const text = decoder.decode(buffer);
let rowCount = 0;
let inQuote = false;
let len = text.length;
for (let i = 0; i < len; i++) {
const char = text[i];
if (char === '"') {
inQuote = !inQuote;
} else if (char === '\n' && !inQuote) {
rowCount++;
}
}
// 如果可疑字符占比 < 5%,认为是纯文本
return suspiciousCount / checkLen < 0.05;
if (len > 0 && text[len - 1] !== '\n') {
rowCount++;
}
return rowCount;
}
_validateTextContent(buffer, extension) {
let contentStr = '';
try {
const decoder = new TextDecoder('utf-8', {
fatal: true,
});
contentStr = decoder.decode(buffer);
} catch (e) {
console.warn('UTF-8 解码失败', e);
return false;
}
if (contentStr.includes('\0')) {
return false;
}
if (extension === 'json') {
try {
JSON.parse(contentStr);
} catch (e) {
console.warn('无效的 JSON 格式');
return false;
}
}
return true;
}
/**
* 执行校验
* @param {File} file 文件对象
* @returns {Promise<boolean>}
*/
validate(file) {
return new Promise((resolve, reject) => {
// 1. 基础对象检查
if (!file || !file.name) return reject('无效的文件对象');
// 2. 大小检查
if (file.size > this.maxSizeMB * 1024 * 1024) {
return reject(`文件大小超出限制 (最大 ${this.maxSizeMB}MB)`);
}
// 3. 后缀名检查
const fileName = file.name.toLowerCase();
const extension = fileName.substring(fileName.lastIndexOf('.') + 1);
// 检查是否在配置的白名单中
const expectedMagic = this.allowedConfig[extension];
if (!expectedMagic) {
return reject(`不支持的文件格式: .${extension}`);
}
// 4. 读取二进制头进行魔数校验
const reader = new FileReader();
reader.onload = (e) => {
const buffer = e.target.result;
let isSafe = false;
// 分支处理:纯文本 vs 二进制
if (expectedMagic === 'TYPE_TEXT') {
if (this._isCleanText(buffer)) {
if (this._validateTextContent(buffer, extension)) {
isSafe = true;
} else {
return reject(`文件异常:.${extension} 文件包含非法二进制内容`);
if (extension === 'json') {
return reject(`文件异常:不是有效的 JSON 文件`);
}
return reject(`文件异常:.${extension} 包含非法二进制内容或编码错误`);
}
if (extension === 'csv' && this.csvMaxRows > 0) {
const rows = this._countCSVRows(buffer);
if (rows > this.csvMaxRows) {
return reject(`CSV 行数超出限制 (当前 ${rows} 行,最大允许 ${this.csvMaxRows} 行)`);
}
}
} else {
// 获取文件头 Hex (读取足够长的字节以覆盖最长的魔数PNG需8字节)
const fileHeader = this._bufferToHex(buffer.slice(0, 8));
// 使用 startsWith 匹配
if (fileHeader.startsWith(expectedMagic)) {
isSafe = true;
} else {
return reject(`文件可能已被篡改 (真实类型与 .${extension} 不符)`);
}
}
if (isSafe) resolve(true);
};
reader.onerror = () => reject('文件读取失败,无法校验');
// 读取前 1KB 进行判断
reader.readAsArrayBuffer(file.slice(0, 1024));
if (expectedMagic === 'TYPE_TEXT' && extension === 'json') {
reader.readAsArrayBuffer(file);
} else {
reader.readAsArrayBuffer(file.slice(0, 2048));
}
});
}
}
// 【demo】
// 如果传入了 allowedExtensions则只使用传入的否则使用全部 KNOWN_SIGNATURES
// const imageValidator = new FileValidator({

View File

@@ -139,7 +139,7 @@ export function createRequest(url, data = {}, method = 'GET', loading = false, h
resolve(resData.data)
return
}
if (msg) {
if (msg && config.showErrorMessage) {
uni.showToast({
title: msg,
icon: 'none'

View File

@@ -10,4 +10,12 @@ export default defineConfig({
viteInjectPopup(),
uni(),
],
server: {
proxy: {
'/app':{
target: 'http://36.105.163.21:30083/rgpp/api',
changeOrigin: true,
}
}
}
});