0
点赞
收藏
分享

微信扫一扫

uniapp 微信小程序 实现上传多个图片

醉东枫 2022-04-29 阅读 55

效果图:
在这里插入图片描述

代码:

upload.vue

<u-upload
	accept="image"
	capture="['album', 'camera']"
	:previewImage="true"
	width="200"
	height="200"
	:fileList="fileList"
	@afterRead="afterRead"
	@delete="deletePic"
	name="uploader-componet"
	multiple
	:maxCount="9"
>
	<div style="background-color: #f4f5f7;width:200rpx;height:200rpx;display: flex;align-items: center;justify-content: center;border-radius: 4rpx;box-sizing: border-box;">
		<u-icon name="camera-fill" color="#D3D4D6" size="50"></u-icon>
	</div>	
</u-upload>

<u-button type="primary" :plain="true" text="提交申请"
	@click="submitRefundApplyHandle()">
</u-button>
<script>
	import refundApi from '@/api/refund.js'
	export default{
		data(){
			return {
				fileList:[],
submitRefundApplyHandle(){
	// this.$refs.refRefundApplyForm.validate().then(res => {
	// 	uni.$u.toast('校验通过')
	// }).catch(errors => {
	// 	uni.$u.toast('校验失败')
	// })
	let formObj = deepCopy(this.refundApplyForm)
	formObj.reasonType = this.transf_reasonType[formObj.reasonType]
	this.applyRefundHandle(formObj)
},
applyRefundHandle(formObj){
	console.log('提交的表单:', formObj,this.fileList)
	const arr_temp = []
	this.fileList.forEach((item,index) => {
		arr_temp.push({name:'image'+index,uri: item.url})
	})
	// formObj.annexFiles = this.fileList
	let requestLength = 0
	const annexFileIds = []
	arr_temp.forEach((ele,index) => {
		refundApi.uploadRefundAnnexFile(arr_temp[index], 'file').then(res => {
			const response = JSON.parse(res)
			console.log('上传照片结果:',response)
			if (response.code === 200) {
				++requestLength
				annexFileIds.push(response.data)
				if(requestLength===arr_temp.length){
					formObj.annexFileIds = annexFileIds.join()
					refundApi.createRefundApply(formObj).then(res => {
						console.log('提交申请结果:',res)
						if (res.code === 200) {
							// 跳转到结果页
							uni.reLaunch({
								url: '/pages/my/refundApply/refundResult?pageMsg=申请成功,请等待人员审核'
							});
						} else {
							uni.showToast({
								title: res.msg,
								icon: 'none',
								duration: 5000,
							})
						}
					})
				}
			} else {

			}
		})
	})

},
// 删除图片
deletePic(event) {
	this.fileList.splice(event.index, 1)
},
afterRead(event) {
	console.log('照片地址:', event)
	// 当设置 mutiple 为 true 时, file 为数组格式,否则为对象格式
	let lists = [].concat(event.file)
	let fileListLen = this.fileList.length
	lists.map((item) => {
		this.fileList.push({
			...item,
			status: 'uploading',
			message: '上传中'
		})
	})
	for (let i = 0; i < lists.length; i++) {
		const url = lists[i].url
		let item = this.fileList[fileListLen]
		this.fileList.splice(fileListLen, 1, Object.assign(item, {
			status: 'success',
			message: '',
			url: url
		}))
		fileListLen++
	}
},

refundResult.vue(用于显示上传成功)

<template>
	<view class="content">
		<view >
			<u--image :showLoading="true" :src="require('static/img/my/submit.png')" width="500rpx" height="500rpx">
			</u--image>
			<view class="text-style">{{message}}</view>
			<view class="mg30">
				<u-button type="primary" :plain="true" text="返回首页"
					@click="backHome()">
				</u-button>
			</view>
		</view>
	</view>
</template>

<script>
	export default{
		data(){
			return{
				message:''
			}
		},
		onLoad:function(option){
			this.message = option.pageMsg
		},
		methods:{
			backHome(){
				uni.switchTab({
					url: '/pages/home/index'
				})
			},
		}
	}
</script>

<style lang="scss" scoped>
	.content{
		margin-top: 100rpx;
		padding: 30rpx;
		display: flex;
		justify-content: center;;
	}
	.text-style{
		color: #aaa;
		text-align: center;
	}
	.mg30{
		margin-top: 30rpx;
	}
</style>

config/request.js

function uploadFile_common (url, file, name, callback = '') {
	const token = uni.getStorageSync('user_token')
	return new Promise((resolve, reject) => {
		console.log('拿到的参数:', url, file, name)
        uni.uploadFile({
			url: baseUrl + url,
            header: { 'Authorization': 'Bearer ' + token, 'Content-Type': 'multipart/form-data' },
			fileType:'image',
            filePath: file.uri,
            name: name,
            success: res => {

            },
            fail: err => {
                reject(err)
                console.log('[上传接口错误:uploadFile_common:',err)
            },
            complete: res => {
                if (callback){
                	return callback(res.data)
                }
                if (res.data.code === 401) {
                    console.log('上传接口401:uploadFile_common')
					try {
						uni.removeStorageSync('user_token')
					} catch (e) {
						console.log('user_token移除失败(uploadFile_common)')
					}
					// 将需要重新执行的接口缓存到一个队列中
					addSubscriber(() => {
						uploadFile_common(url, file, name, formData, resolve)
					})
					if (isRefreshing) {
						getNewToken().then(() => {
							// 依次去执行缓存的接口
							onAccessTokenFetched();
							isRefreshing = true;
						}).catch(e => {
							console.log('getNewToken错误(uploadFile_common):', e)
						})
                   }
                   isRefreshing = false; 
                } else {
                    resolve(res.data)
                }
            }
        })
	})
}
export { uploadFile_common }

refund.js

import {uploadFile_common} from '@/config/request.js'
export default {
	// 上传申请照片
	uploadRefundAnnexFile(file, name) {
		return uploadFile_common('/wechat/selfPrint/refundApply/uploadRefundApplyAnnexFile', file, name)
	},

}
举报

相关推荐

0 条评论