uni-app上传单个或多个图片

<template>
	<view class="selpow">
		<view class="oper">
			<view :style="{ paddingTop: safeAreaInsets?.top + 'rpx' }" class="nav">
				<view class="oper_q">
					<uni-nav-bar left-icon="left" border="false" title="任务处理" style="width: 90%;"
						@clickLeft="handleBack" />
				</view>
			</view>
			<view class="oper_a">
				<view class="oper_aq">
					<view class="oper_aqq">
						<view>任务开始日期:</view>
						<view class="redac_q">
							<view class="uni-list-cell-db">
								{{ kais }}
							</view>
						</view>
					</view>
					 <view class="oper_aqq">
						<view>任务结束日期:</view>
						<view class="redac_q">
							<view class="uni-list-cell-db">
								{{ jies || "未完成" }}
							</view>
						</view>
					</view>
					<view class="oper_aqq">
						<view>问题点处理详情:</view>
					</view>
					<view class="oper_aqq">
						<view class="oper_akiy">
							<uni-easyinput type="textarea" v-model="remark" placeholder="请输入内容"></uni-easyinput>
						</view>
					</view>
					<view class="oper_aqq">
						<view>上传图片:</view>
						<view>
							<button @click="chooseImage">选择图片</button>
							<view v-for="(image, index) in imageSrcs" :key="index" class="image-item">
								<image :src="image" style="width: 200rpx; height: 200rpx;"></image>
								<button @click="deleteImage(index)" class="delete-button">x</button>
							</view>
						</view>
					</view>
					<view class="oper_aqq">
						<button type="primary" style="width: 40%;" @click="handleSave">提交</button>
					</view>
					<!-- <view>
						{{imgs}}
					</view> -->
				</view>
			</view>
		</view>
	</view>
</template>

<script setup lang="ts">
	import { ref, watch } from "vue";
	import { onLoad } from '@dcloudio/uni-app';
	import { subworkorderresult } from '@/src/api/api.js';

	const workOrderId = ref('');
	const kais = ref('');
	const jies = ref('');
	const remark = ref('');
	const imgs = ref([]);
	const imageSrcs = ref([]);
	const nar = ref();
	const njjiy=ref();

	// 获取日期
	function getFormattedDate() {
		const date = new Date();
		const year = date.getFullYear();
		const month = (date.getMonth() + 1).toString().padStart(2, '0');
		const day = date.getDate().toString().padStart(2, '0');
		return `${year}-${month}-${day}`;
	};

	// 返回上一页按钮点击事件处理函数
	const handleBack = () => {
		uni.navigateBack();
	};

	//保存按钮点击事件处理函数
	const handleSave = () => {
		jies.value = getFormattedDate();

		// 检查 remark 是否为空
		if (!remark.value.trim()) {
			uni.showToast({
				title: '请填入相关问题点处理详情',
				icon: 'none'
			});
			return; // 阻止表单提交
		}

		// 检查 imageSrcs 是否为空
		if (imageSrcs.value.length === 0) {
			uni.showToast({
				title: '请上传处理图片',
				icon: 'none'
			});
			return; // 阻止表单提交
		}

		subworkorderresult(imgs.value, remark.value, workOrderId.value).then(response => {
			nar.value = response.data;
			// console.log('提交成功', response);
			uni.showToast({
				title: '提交成功',
				icon: 'success'
			});
			
		}).catch(error => {
			console.error('提交失败', error);
			
		});
		uni.navigateBack();

	};

	// 选择图片
	const chooseImage = () => {
		uni.chooseImage({
			count: 9, // 最多选择9张图片
			sizeType: ['original', 'compressed'],
			sourceType: ['album', 'camera'],
			success: (res) => {
				const tempFilePaths = res.tempFilePaths;
				imageSrcs.value = [...imageSrcs.value, ...tempFilePaths];
				uploadImages(tempFilePaths);
			},
		});
	};

	const uploadImages = (filePaths) => {
    const isSingleImage = filePaths.length === 1;
    const uploadUrl = isSingleImage ? 'https://ems.xuperenergy.cn/dev-api/appcommon/upload' : 'https://ems.xuperenergy.cn/dev-api/appcommon/uploads';

    filePaths.forEach((filePath) => {
        const token = uni.getStorageSync("token");
        uni.uploadFile({
            url: uploadUrl,
            filePath: filePath,
            name: 'file',
            header: {
                'Authorization': `Bearer ${token}` // 使用Bearer Token
            },
           success: (uploadFileRes) => {
               if (typeof uploadFileRes.data === 'string' && uploadFileRes.data.trim()) {
                   try {
                       const responseData = JSON.parse(uploadFileRes.data);
                       const newFilePath = responseData.url;
                       imgs.value.push(newFilePath);
                   } catch (e) {
                       console.error('JSON解析错误:', e);
                   }
               } else {
                   console.error('上传文件响应数据为空或格式不正确');
               }
           },

            fail: (err) => {
                console.error('图片上传失败:', err);
                if (err.errMsg.includes('ECONNRESET')) {
                    console.error('网络连接被重置');
                }
            },
            complete: () => {
                console.log('图片上传完成');
            }
        });
    });
};


	// 删除图片
	const deleteImage = (index) => {
		imageSrcs.value.splice(index, 1);
		imgs.value.splice(index, 1);
	};

	// 监听 remark 的变化
	watch(remark, (newValue) => {
		// console.log('输入的内容:', newValue);
	});

	// 处理字符串 "null" 的函数
	const handleNullString = (value, defaultValue = '') => {
		return value === "null" ? defaultValue : value;
	};

	onLoad((options) => {
		workOrderId.value = handleNullString(options.workOrderId);
		kais.value = handleNullString(options.kais);
	});
</script>

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值