uni-app-cloud中使用手动上传图片

367 阅读1分钟

uni-app-cloud中使用手动上传图片

纯属个人学习记录及其使用

1、选择本地图片--uni.chooseImage()

2、预览图片--uni.previewImage()

3、点击删除--arr.splice(e, 1)

4、上传图片到云存储-- uniCloud.uploadFile()

使用数组循环的方式上传到云端

上传到云端之后获取到图片的 URL ,便于后期加入到数组空
<template>
	<view class="file">
		<view class="uploadGroup">
			<view class="box" v-for="(item,index) in temFile" :key="index">
				<image :src="item.path" mode='aspectFill' @click="clickImg(index)"></image>
				<view class="close" @click="onClose(index)">x</view>
			</view>
			<view class="box add" @click="addFile" v-if="temFile.length < 9">+</view>
		</view>

		<button @click="onUpload">确认上传</button>

	</view>
</template>

<script>
	export default {
		data() {
			return {
				temFile: [],
				maxSize: 9,
				picArr: []
			};
		},

		methods: {

			// 选择本地图片
			addFile() {
				uni.chooseImage({
					count: this.maxSize,
					success: res => {
						console.log(res);
						let oldTem = this.temFile
						let newTem = [...oldTem, ...res.tempFiles]
						newTem = newTem.slice(0, 9) // 截取九张图片
						this.temFile = newTem

						// console.log(this.temFile);
					}
				})
			},

			// 预览图片
			clickImg(e) {
				// console.log(e);
				let arr = this.temFile.map(item => {
					return item.path
				})
				uni.previewImage({
					current: e, // 图片的索引
					urls: arr // 图片的 URL 数组
				})
			},

			// 点击删除
			onClose(e) {
				// console.log(e);
				this.temFile.splice(e, 1)
			},

			// 上传图片到云存储
			onUpload() {
				// 使用 async 定义方法 会返回一个 promise 对象
				// map 方法返回一个新的数组
                                // 使用数组循环的方式上传到云端
				let newArr = this.temFile.map(async item => {
					let p = await this.uploadFun(item)
					// console.log(p);

					return p
				})
                                 
                                 // 上传到云端之后获取到图片的 URL ,便于后期加入到数组空
				// Promise.all() 对数组形式的 promise 对象进行返回 
				Promise.all(newArr).then(res => {
					let arr = res.map(item => {
						return item.fileID
					})

					this.picArr = arr
					// console.log(this.picArr);
				})

			},

			// 返回的是一个 promise 对象
			uploadFun(item) {
				return uniCloud.uploadFile({
					filePath: item.path, // 要上传的文件对象
					cloudPath: item.name // 使用腾讯云时,表示文件的绝对路径,包含文件名。使用阿里云时,cloudPath为云端文件名
				})
			},
		}
	}
</script>

<style lang="scss" scoped>
	.uploadGroup {
		padding: 30rpx;
		display: flex;
		flex-wrap: wrap;

		.box {
			position: relative;
			width: 200rpx;
			height: 200rpx;
			background-color: #eee;
			margin-right: 15rpx;
			margin-bottom: 15rpx;

			image {
				width: 100%;
				height: 100%;

			}

			.close {
				box-sizing: border-box;
				position: absolute;
				right: 0;
				top: 0;
				width: 50rpx;
				height: 50rpx;
				background: rgba(0, 0, 0, .5);
				padding: 0 0 20rpx 10rpx;
				color: #fff;
				border-radius: 0 0 0 80rpx;
				display: flex;
				justify-content: center;
				align-items: center;
			}
		}

		.add {
			font-size: 80rpx;
			display: flex;
			align-items: center;
			justify-content: center;
			color: #888;
		}
	}
</style>