uni-app 使用API中的uni.chooseImage 上传照片以及uni.previewImage图片预览(身份证照片为例)

在uni-app项目中通常需要用户上传照片,如下图所示:

其中部分参数为本项目中请求接口时所需要的,可以根据需求自行修改对应的参数等,代码如下:

<template>
	<div class="container">
		<div class="user-info">
			<div class="id-info">身份证照片</div>
			<div class="tips">*请上传本人的身份证照片(单张照片限制1M以内)</div>
			<div>
				<img class="img-info" :src="card_front ? card_front : img_url+'/id-f.png'" @click="upLondImg('cardFront',card_front)">
			</div>
			<div>
				<img class="img-info" :src="card_back ? card_back : img_url+'/id-z.png'" @click="upLondImg('cardBack',card_back)">
			</div>
		</div>
		<div class="user-info item">
			<div class="id-info">个人证件照</div>
			<div class="tips">*请上传近期白底或蓝底免冠正面证件照</div>
			<div>
				<img class="upload" :src="stu_card ? stu_card : img_url+'/jh.png'" @click="upLondImg('personalPhoto',stu_card)">
			</div>
		</div>
		<button class="submit-btn" @click="subBtn" v-if="stu_info.label != 2">提交</button>
	</div>
</template>

<script>
	export default {
		data() {
			return {
				img_url: this.$http.img_url(),
				img: '',
				Path: {},
				stu_card: '',
				card_back: '',
				card_front: '',
				stu_info: null
			}
		},
		onLoad(option) {
			this.stu_info = JSON.parse(option.photo)
			this.card_front = this.stu_info.card_front
			this.card_back = this.stu_info.card_back
			this.stu_card = this.stu_info.stu_card
		},
		methods: {
			subBtn() {
				if (!this.card_front) {
					uni.showToast({
						title: '请上传身份证正面照',
						icon: 'none'
					})
					return
				}
				if (!this.card_back) {
					uni.showToast({
						title: '请上传身份证反面照',
						icon: 'none'
					})
					return
				}
				if (!this.stu_card) {
					uni.showToast({
						title: '请上传个人证件照',
						icon: 'none'
					})
					return
				}
				this.$http.post('personal/identity', {
					stu_card: this.stu_card,
					card_back: this.card_back,
					card_front: this.card_front
				}).then(res => {
					if (res.code == 200) {
						uni.showToast({
							title: '提交成功',
							success: () => {
								setTimeout(() => {
									uni.navigateBack({
										delta: 1
									});
								}, 1000);
							}
						})
					}
				})
			},
			upLondImg(path,src) {
				if (this.stu_info.label == 2) {
					 uni.previewImage({
						urls: [src]
					})
					return
				}
				
				this.$http.uniApi({
					events: uni.chooseImage
				}, {
					count: 1,
					sizeType: ['original', 'compressed']
				}).then(res => {
					this.$http.upLoad({
						img: res.tempFilePaths[0],
						path: path
					}).then(res => {
						if (path == 'cardFront') {
							this.card_front = JSON.parse(res).data.url
						} else if (path == 'cardBack') {
							this.card_back = JSON.parse(res).data.url
						} else {
							this.stu_card = JSON.parse(res).data.url
						}
					})
				})

			}
		}
	}
</script>

通过以上的设置就可以完整的实现身份证照片上传以及图片的预览

posted on 2021-08-04 15:52  jimyking  阅读(2382)  评论(0编辑  收藏  举报