Procházet zdrojové kódy

上传功能初始化

zhangxike před 2 měsíci
rodič
revize
62f2b0bdf9

+ 35 - 40
pages/work/record/InfoList.uvue

@@ -19,39 +19,41 @@
     <!-- #ifdef APP -->
     <scroll-view style="flex:1">
     <!-- #endif -->
-      <view class="download-card" v-for="(item, index) in downloads" :key="index" @click="enterItem(item.pdid)">
-        <view class="info-row">
-          <text class="label">工作令:</text>
-          <text class="value">{{ item.workorder }}</text>
-        </view>
-        <view class="info-row">
-          <text class="label">产品名称:</text>
-          <text class="value">{{ item.invname }}</text>
-        </view>
-        <view class="info-row">
-          <text class="label">物料编码:</text>
-          <text class="value">{{ item.graphid }}</text>
-        </view>
-        <view class="info-row">
-          <text class="label">路卡号:</text>
-          <text class="value">{{ item.cardno }}</text>
-        </view>
-        <view class="info-row">
-          <text class="label">产品码:</text>
-          <text class="value">{{ item.productno }}</text>
-        </view>
-        <view class="info-row">
-          <text class="label">最近更新时间:</text>
-          <text class="value">{{ item.updatetime == "" ? item.createtime : item.updatetime }}</text>
-        </view>
-        <view class="info-row">
-          <text class="label">进度:</text>
-          <text class="process-value" :class="{
-            'bg-green': item.statusRecordCount === item.totalRecord,
-            'bg-yellow': item.statusRecordCount < item.totalRecord,
-            'bg-black': item.statusRecordCount === 0
-          }"> {{ item.statusRecordCount }} / {{ item.totalRecord }} </text>
-        </view>
+      <view class="download-card" v-for="(item, index) in downloads" :key="index" >
+		<view @click="enterItem(item.pdid)">
+			<view class="info-row">
+			  <text class="label">工作令:</text>
+			  <text class="value">{{ item.workorder }}</text>
+			</view>
+			<view class="info-row">
+			  <text class="label">产品名称:</text>
+			  <text class="value">{{ item.invname }}</text>
+			</view>
+			<view class="info-row">
+			  <text class="label">物料编码:</text>
+			  <text class="value">{{ item.graphid }}</text>
+			</view>
+			<view class="info-row">
+			  <text class="label">路卡号:</text>
+			  <text class="value">{{ item.cardno }}</text>
+			</view>
+			<view class="info-row">
+			  <text class="label">产品码:</text>
+			  <text class="value">{{ item.productno }}</text>
+			</view>
+			<view class="info-row">
+			  <text class="label">最近更新时间:</text>
+			  <text class="value">{{ item.updatetime == "" ? item.createtime : item.updatetime }}</text>
+			</view>
+			<view class="info-row">
+			  <text class="label">进度:</text>
+			  <text class="process-value" :class="{
+			    'bg-green': item.statusRecordCount === item.totalRecord,
+			    'bg-yellow': item.statusRecordCount < item.totalRecord,
+			    'bg-black': item.statusRecordCount === 0
+			  }"> {{ item.statusRecordCount }} / {{ item.totalRecord }} </text>
+			</view>
+		</view>  
 		
 		<view class="info-row">
 			<button class="btn btn-second" @click="upload">
@@ -186,13 +188,6 @@
   
   const upload = async (e : any) => {
     console.log("开始上传...")
-	if(productNo.value == null || productNo.value == '') {
-		uni.showToast({
-		  title: '请先扫描或者输入产品号',
-		  icon: 'error'
-		});
-		return
-	}
     uploadDataToAPI(productNo.value, () => {
 	  // 回调函数中执行刷新,确保数据都保存好,进度条跑完
 	  uni.reLaunch({ url: '/pages/work/record/InfoList' })

+ 5 - 4
pages/work/record/RecordList.uvue

@@ -282,15 +282,16 @@
 					}
 
 					if (imgname.length == 0) {
-						updatedData += ',status=1 '
+						updatedData += ',status=1  '
 					} else if (imgname.length < record.num) {
 						updatedData += ',status=2 '
+					} else if (imgname.length + 1 == record.num){
+						updatedData += ',status=3 '
 					}
 
 					updateData('app_media_record', updatedData, 'sxid', record.sxid.toString()).then((res : UTSJSONObject) => {
-						let dataList = res?.['data'] as UTSJSONObject[] ?? Array<UTSJSONObject>()
-						if (dataList != null && dataList.length > 0) {
-							console.log(dataList[0])
+						let dataRes = res?.['data'] as boolean ?? false
+						if (dataRes) {
 							uni.showToast({
 								title: "删除成功!",
 							});

+ 107 - 70
utils/dataProcessor.uts

@@ -52,17 +52,31 @@ export type PhotoFilesExample = {
 	_id ?: string,
 }
 
+export const showProgress = (index : number, title : string) => {
+	// 在Android设备上,需要给hideLoading和showLoading之间添加延迟
+	// 先隐藏之前的加载提示
+	uni.hideLoading();
+	// 添加50ms的延迟,确保hideLoading完全执行后再显示新的进度
+	setTimeout(() => {
+		uni.showLoading({
+			title: `正在${title}第${index}个任务数据`,
+			mask: true
+		});
+	}, 50);
+}
+
+//声像任务下载
 export const downloadDataFromAPI = async (productCode : string, callback ?: () => void) : Promise<boolean> => {
 	try {
 		uni.showLoading({ title: '任务开始下载' });
 		const apiToken = await getTokenFromApi();
-		
-		if(apiToken==null || apiToken == '') {
+
+		if (apiToken == null || apiToken == '') {
 			uni.hideLoading();
 			uni.showToast({ title: `获取Token失败,请联系技术IT`, icon: 'error' });
 			return false
 		}
-		
+
 		//校验是否已经存在未执行的产品号,若已经存在则提示用户该产品号是否需要被覆盖,
 		//如果没有则直接保存。如果有存在已经在执行中的产品号,则提示已存在执行中的任务
 		const infoJson = await getLatestRecord(productCode, null);
@@ -124,21 +138,6 @@ export const downloadDataFromAPI = async (productCode : string, callback ?: () =
 			}
 		}
 
-		// 创建进度条 - 适配Android设备的解决方案
-		const showProgress = (index : number) => {
-			// 在Android设备上,需要给hideLoading和showLoading之间添加延迟
-			// 先隐藏之前的加载提示
-			uni.hideLoading();
-			// 添加50ms的延迟,确保hideLoading完全执行后再显示新的进度
-			setTimeout(() => {
-				uni.showLoading({
-					title: `正在下载第${index}个任务数据`,
-					mask: true
-				});
-			}, 50);
-		};
-
-
 		// 使用Promise处理HTTP请求,避免嵌套Promise
 		return new Promise<boolean>((resolve) => {
 			uni.request({
@@ -169,13 +168,13 @@ export const downloadDataFromAPI = async (productCode : string, callback ?: () =
 													// 使用async/await处理循环中的异步操作
 													const processAllRecords = async () => {
 														// 创建一个Map来跟踪不同photoitem的计数
-														const photoItemCounter: Map<string, number> = new Map();
-														
+														const photoItemCounter : Map<string, number> = new Map();
+
 														for (var i = 0; i < recordList.length; i++) {
 															// 更新进度
 															processedRecords++;
-															showProgress(processedRecords);
-																
+															showProgress(processedRecords, '下载');
+
 															const record : MediaRecordData = recordList[i] as MediaRecordData;
 															// 获取各个字段的值
 															const photoitem = record.photoitem as string;
@@ -183,11 +182,11 @@ export const downloadDataFromAPI = async (productCode : string, callback ?: () =
 															if (!photoItemCounter.has(photoitem)) {
 																photoItemCounter.set(photoitem, 1);
 															} else {
-															const currentCount = photoItemCounter.get(photoitem);
-															photoItemCounter.set(photoitem, (currentCount != null ? currentCount : 0) + 1);
-														}
-														const senum = photoItemCounter.get(photoitem);
-														const finalSenum = senum != null ? senum : 1;
+																const currentCount = photoItemCounter.get(photoitem);
+																photoItemCounter.set(photoitem, (currentCount != null ? currentCount : 0) + 1);
+															}
+															const senum = photoItemCounter.get(photoitem);
+															const finalSenum = senum != null ? senum : 1;
 															const partno = record.partno;
 															const part = record.part;
 															const pk = record.pk;
@@ -246,7 +245,7 @@ export const downloadDataFromAPI = async (productCode : string, callback ?: () =
 																										// 保存失败也继续处理下一张,但记录错误
 																										setTimeout(() => {
 																											reject(err);
-																										}, 1000);
+																										}, 500);
 																									}
 																								});
 																							}, 500); // 等待500ms确保文件完全下载
@@ -332,70 +331,108 @@ export const downloadDataFromAPI = async (productCode : string, callback ?: () =
 }
 
 
+//声像任务上传
 export const uploadDataToAPI = async (productCode : string, callback ?: () => void) : Promise<boolean> => {
 
 	try {
 		//暂定需要上传的数据文件
 		//const infoJson = await getLatestRecord(productCode, null);
 		const apiToken = await getTokenFromApi();
-        
-		const showProgress = (index : number) => {
-			// 在Android设备上,需要给hideLoading和showLoading之间添加延迟
-			// 先隐藏之前的加载提示
+		if (apiToken == null || apiToken == '') {
 			uni.hideLoading();
-			// 添加50ms的延迟,确保hideLoading完全执行后再显示新的进度
-			setTimeout(() => {
-				uni.showLoading({
-					title: `正在上传第${index}个任务数据`,
-					mask: true
-				});
-			}, 50);
-		}; 
+			uni.showToast({ title: `获取Token失败,请联系技术IT`, icon: 'error' });
+			return false
+		}
 
 
-		getJoinList('app_media_record as r', 'app_media_info as i', 'r.*,i.productno', 'r.pid=i.pdid', 'i.productno', productCode, null).then((res : UTSJSONObject) => {
+		getJoinList('app_media_record as r', 'app_media_info as i', 'r.*,i.productno', 'r.pid=i.pdid', 'i.productno', productCode, null).then(async (res : UTSJSONObject) => {
 			let dataList = res?.['data'] as UTSJSONObject[] ?? Array<UTSJSONObject>()
+			console.log(dataList);
 			if (dataList != null && dataList.length > 0) {
-				let imgList = dataList.filter(item => item.getNumber("status") == 3 && item.getString("urlpdt") != '')
-				let uploadFiles = Array<string>()
-				let uploadNames = Array<string>()
-				if (imgList.length > 0) {
-					imgList.forEach(img => {
-						let urlpdtStr = img['urlpdt'] as string
-						let nameStr = img['imgname'] as string
-						let urlArr = urlpdtStr.split(",")
-						uploadFiles.push(...urlArr);
-						let nameArr = nameStr.split(",")
-						uploadNames.push(...nameArr)
-					});
-				}
-				if (uploadFiles.length === 0) {
+				let doneRecordList = dataList.filter(item => item.getString("status") == '3')
+				// console.log("uploadFiles", uploadFiles);
+				if (doneRecordList.length === 0) {
 					uni.showToast({ title: '上传图片数据为空', icon: 'error' });
 					return;
 				}
+				let processStep = 1;
+				for (let index = 0; index < dataList.length; index++) {
+					const record = dataList[index];
 
-				uploadFiles.forEach((filePath, index) => {										
+					if (record.getString('urlpdt') == '' || record.getString('urlpdt') == null
+						|| record.getString('pk') == '' || record.getString('pk') == null) {
+						continue
+					}
+					showProgress(processStep, '上传');
 					//文件上传
-					upload({
-					  apiUrl: globalConfig.apiUrl,
-					  name: uploadNames[index],
-					  seq: index, 
-					  filePath: filePath,
-					  formData: {
-						   //传递数据
-						   
-					  }
-					});
-				});
+					let urlpdtStr = record.getString('urlpdt')
+					let pk = record.getString('pk')
+					let urlArr = urlpdtStr?.split(",") ?? []
+					
+					for (let j = 0; j < urlArr.length; j++) {
+						let path = urlArr[j];
+						const fullFilePath = `${uni.env.USER_DATA_PATH}` + path;
+						console.log(`开始上传文件: ${fullFilePath}, 索引: ${j}, apiToken: ${apiToken}, billid: ${pk}`);
+						await new Promise<void>((resolve, reject) => {
+							// 使用uni.uploadFile进行文件上传
+							uni.uploadFile({
+								url: 'http://192.168.43.62:8080/api/images/upload',
+								filePath: fullFilePath,
+								name: 'file', // 文件参数名
+								header: {
+									'token': apiToken
+								},
+								formData: {
+									'billid': pk
+								},
+								success: (uploadRes) => {
+									if (uploadRes.statusCode === 200) {
+										console.log(`文件${path}上传成功`, uploadRes);
+										// 解析响应数据
+										const resData = JSON.parse(uploadRes.data) as UTSJSONObject;
+										console.log(resData)
+										if (resData?.['_id'] != null && resData?.['_id'] != '') {
+											setTimeout(() => {
+												resolve();
+											}, 3000);
+										} else {
+											setTimeout(() => {
+												reject('');
+											}, 500);
+										}
+									}
+								},
+								fail: (err) => {
+									console.error(`文件${path}上传失败`, err);
+									uni.showToast({
+										title: `文件${j}上传失败: ${err.errMsg != null ? err.errMsg : '网络错误'}`,
+										icon: 'error'
+									});
+									setTimeout(() => {
+										reject(err); // 在fail回调中调用reject
+									}, 500);
+								},
+								complete: () => {
+									console.log(`文件${path}上传完成`);
+								}
+							});
+						}).catch(err => {
+							// 捕获上传失败的错误,但继续上传下一个文件
+							console.log(`当前文件上传失败,但继续下一个文件上传,异常 ${err}`);
+						});
+					}
+					processStep++;
+				}
 
 			}
 		})
-	}
-	catch (error) {
+	} catch (error) {
 		console.error(error);
-		uni.showToast({ title: '上传失败,请重试', icon: 'error' });
+		// uni.showToast({ title: '上传失败,请重试', icon: 'error' });
 		uni.hideLoading();
 		return false;
 	}
+	
+	uni.hideLoading();
 	return true;
 }