我的需求是在表单中,点击添加图片,只能选一张本地图片或拍照一张数量的设置会在下面提到)。(项目写的很急,效果应该是没什么问题都是测过的,但是代码写不够优雅,我自己都能看出来有很多地方写的太繁琐,之后有空在慢慢改吧)

        使用uni.chooseImage()选择图片并在成功的回调中给this.imgBg赋值(this.imgBg是image需要的src),使用plus.zip.compressImage()进行图片压缩给that.imgBgArr赋值(that.imgBgArr是上传给服务器的参数),在成功的回调中使用uni.uploadFile(OBJECT)将本地资源上传到服务器。

        后端会解析拿到的图片资源并返回一个临时路径和绝对路径,在成功的回调中给this.imgBgUrlimgBgArrUrl赋值,最后在提交表单时,将临时路径绝对路径加到表单接口参数中一起调用接口上传。最后会加一些其他功能函数,比如图片删除(直接给图片赋空字符串),图片预览(调用uni.previewImage(OBJECT)方法)。

        PS:关于最后一步,为什么非要先把文件资源上传给服务器,后端再返回一个临时路径和绝对路径,最后再把这两个路径原封不动的传给后端。我最开始也不是很理解为什么明明这两个路径是后端给我的,难道后端自己在往DB里存的时候就不能获取吗。之后和后端的哥们讨论了一下,他的解释是:完全可以做到,但是如果把接受解析上传的图片资源,生成路径,再把路径存到DB中,最后到前端接受到成功的信息,这一套下来用户需要等待大量(可能吧)的时间,所以为了提升用户体验,尽量不要把所有的处理都放在这一次事件里做。

template部分:因为只有一张图片,所以直接用的字符串,如果需要多张,可以用数组做v-for

<!-- 背景图片 -->
<view class="bg-default" v-if="imgBg === ''" @click="chooseImg()">
    <view class="" style="width: 70rpx; height: 70rpx;">
	    <image class="my_img" :src="avatarUrl"></image>
	</view>
	<view class="text-default">添加背景图片</view>
</view>

<view class="add_img_view" v-else>
	<view class="add_img_item" @click="bindImg()">
		<image :src="imgBg"></image>
		<view class="add_close" @click.stop="deleteImg()">
			<uni-icons type="clear" size="15" color="#4977F9"></uni-icons>
		</view>
	</view>
</view>

data部分:

data() {
	return {
		// 上传默认图片
		avatarUrl: '../../static/myCheck/default.png',
		// 背景图展示
		imgBg: '',
		// 背景图预览
		imgBgArray: [],
		// 背景图路径
		imgBgArr: '',
		// 上传的背景临时路径
		imgBgUrl: '',
		// 上传的背景图绝对路径
		imgBgArrUrl: '',
	}
},

methods部分:

// 选择背景图片
			chooseImg() {
				const isIosTrue = uni.getStorageSync('IOS_FIRST_CAMERA')
				if (this.phoneType === 'ios' && isIosTrue !== 'false') {
					// 设为false就代表不是第一次开启相机
					uni.setStorageSync('IOS_FIRST_CAMERA', 'false')
				}
				uni.chooseImage({
					sizeType: "compressed",
                    // 选择图片的数量
					count: 1,
					success: res => {
						// console.log(res.tempFilePaths[0])
						this.imgBg = res.tempFilePaths[0]
						this.imgBgArray = res.tempFilePaths
						this.app_img(0, res)
					},
				})
			},
			// 图片压缩
            //(这里实际上一开始是要求选择多张图片的,所以将res作为一个数组进行的处理,
            // 后期需求变更,写的比较急,就没改,直接给num传了一个0,默认从数组第一个开始,
            // 然后通过判断数组的length来直接return掉。)
			app_img(num, res) {
				let that = this
				if (Number(num) === Number(res.tempFiles.length)) {
					return
				}
				let index = res.tempFiles[num].path.lastIndexOf(".")
				let img_type = res.tempFiles[num].path.substring(index, res.tempFiles[num].path.length)
				let img_yuanshi = res.tempFiles[num].path.substring(0, index)
				let d2 = new Date().getTime()
				plus.zip.compressImage({
					src: res.tempFiles[num].path,
					dst: img_yuanshi + d2 + img_type,
					quality: 10
				}, function(e) {
						that.imgBgArr = e.target
						that.postImg(that.imgBgArr)
					    that.app_img(num + 1, res)
				})
			},
			// 删除图片
			deleteImg() {
				this.imgBg = ''
				this.imgBgAr = ''
				this.imgBgArrUrl = ''
			},
			// 点击图片
			bindImg() {
				if(this.imgBgArray.length !== 0){
					console.log(index)
					uni.previewImage({
						urls: this.imgBgArray,
						current: 0
					})
				}
			},
// 上传图片
			postImg(imgFilePaths) {
				uni.uploadFile({
					url: baseUrl.apiUrl + '/xxx/xxx',
					filePath: imgFilePaths,
					name: 'file',
					success: (uploadFileRes) => {
						let imgValue = JSON.parse(uploadFileRes.data)
						this.imgBgArrUrl = imgValue.data.absoluteUrl
						this.imgBgUrl = imgValue.data.url
					}
				});
			},

Logo

为开发者提供学习成长、分享交流、生态实践、资源工具等服务,帮助开发者快速成长。

更多推荐