uniapp, uview - image upload (single image upload, multiple image upload, multiple group photo upload, image echo)

1. Introduction

The upload function of uView component, single image upload, multiple image upload, etc.
Official document address:
https://www.uviewui.com/components/upload.html

2. Steps

(1) Single image upload

1. Effect demonstration:

You can only upload one image. After selecting it, the upload button disappears. Of course, if the image is inappropriate, delete it and replace it with another one, but you can only upload one image.
Insert image description here

2. Code:
<template>
	<view class="content">
		<!-- 上传图片 -->
		<u-upload :fileList="fileList1" @afterRead="afterRead" @delete="deletePic" name="1" :multiple="false" :maxCount="1" width="112rpx" height="109rpx" :deletable="true" :previewImage="true">
		    <!-- 这张图片就是自定义的图片,地址填写自己本地的就行 -->
			<image src="/static/function/uploadImg.png" mode="widthFix" style="width: 112rpx;height: 110rpx;"></image>
		</u-upload>
	</view>
</template>

<script>
	export default {
      
      
		data() {
      
      
			return {
      
      
				// 上传图片
				fileList1: [],
			}
		},
		onLoad() {
      
      

		},
		methods: {
      
      
		    //删除图片
			deletePic(e) {
      
      
				console.log(e);
				this[`fileList${ 
        e.name}`].splice(e.index, 1)
			},
			// 新增图片
			async afterRead(event) {
      
      
				console.log(event)
				// 当设置 mutiple 为 true 时, file 为数组格式,否则为对象格式
				let lists = [].concat(event.file)
				let fileListLen = this[`fileList${ 
        event.name}`].length
				lists.map((item) => {
      
      
					this[`fileList${ 
        event.name}`].push({
      
      
						...item,
						status: 'uploading',
						message: '上传中'
					})
				})
				for (let i = 0; i < lists.length; i++) {
      
      
					const result = await this.uploadFilePromise(lists[i].url)
					let item = this[`fileList${ 
        event.name}`][fileListLen]
					this[`fileList${ 
        event.name}`].splice(fileListLen, 1, Object.assign(item, {
      
      
						status: 'success',
						message: '',
						url: result
					}))
					fileListLen++
				}
			},
			//上传图片
			uploadFilePromise(url) {
      
      
				return new Promise((resolve, reject) => {
      
      
					let a = uni.uploadFile({
      
      
						//url: this.$common.domain+'/api/common/upload', // 仅为示例,非真实的接口地址
						url:'http://192.168.2.21:7001/upload', // 仅为示例,非真实的接口地址
						filePath: url,
						name: 'file',
						formData: {
      
      
							user: 'test'
						},
						success: (res) => {
      
      
							let data=JSON.parse(res.data) //最终传给的是字符串,这里需要转换格式
							resolve(data.data.url)
						}
					});
				})
			},
		}
	}
</script>

<style lang="scss">
</style>

(2) Uploading multiple pictures

1. Effect demonstration:

You can select multiple images at one time. I limit it to two here. If you upload two full images, the uploaded logo will not be displayed. Click on the image to preview.
Insert image description here

2. Code:
<template>
	<view class="content">
		<!-- 上传图片 -->
		<u-upload :fileList="fileList1" @afterRead="afterRead" @delete="deletePic" name="1" :multiple="true" :maxCount="2" width="112rpx" height="109rpx" :deletable="true" :previewImage="true">
		    <!-- 这张图片就是自定义的图片,地址填写自己本地的就行 -->
			<image src="/static/function/uploadImg.png" mode="widthFix" style="width: 112rpx;height: 110rpx;"></image>
		</u-upload>
	</view>
</template>

<script>
	export default {
      
      
		data() {
      
      
			return {
      
      
				// 上传图片
				fileList1: [],
			}
		},
		onLoad() {
      
      

		},
		methods: {
      
      
		    //删除图片
			deletePic(e) {
      
      
				console.log(e);
				this[`fileList${ 
        e.name}`].splice(e.index, 1)
			},
			// 新增图片
			async afterRead(event) {
      
      
				console.log(event)
				// 当设置 mutiple 为 true 时, file 为数组格式,否则为对象格式
				let lists = [].concat(event.file)
				let fileListLen = this[`fileList${ 
        event.name}`].length
				lists.map((item) => {
      
      
					this[`fileList${ 
        event.name}`].push({
      
      
						...item,
						status: 'uploading',
						message: '上传中'
					})
				})
				for (let i = 0; i < lists.length; i++) {
      
      
					const result = await this.uploadFilePromise(lists[i].url)
					let item = this[`fileList${ 
        event.name}`][fileListLen]
					this[`fileList${ 
        event.name}`].splice(fileListLen, 1, Object.assign(item, {
      
      
						status: 'success',
						message: '',
						url: result
					}))
					fileListLen++
				}
			},
			//上传图片
			uploadFilePromise(url) {
      
      
				return new Promise((resolve, reject) => {
      
      
					let a = uni.uploadFile({
      
      
						//url: this.$common.domain+'/api/common/upload', // 仅为示例,非真实的接口地址
						url:'http://192.168.2.21:7001/upload', // 仅为示例,非真实的接口地址
						filePath: url,
						name: 'file',
						formData: {
      
      
							user: 'test'
						},
						success: (res) => {
      
      
							setTimeout(() => {
      
      
								resolve(res.data.data)
							}, 1000)
						}
					});
				})
			},
		}
	}
</script>

<style lang="scss">
</style>

3. Other supplements

Insert image description here
If there are multiple uploads on a page, the operation is not very complicated, and everyone uses the same method.
Insert image description here
Just move it over as a whole and use it.
Insert image description here
The request interface needs to be processed with join

getData() {
    
    
	let images=[]
	this.fileList1.forEach((item)=>{
    
    
		images.push(item.url)
	})
	this.$common.request('post', '/Coupon/addCoupon', {
    
    
		image:images.join(','),
	}).then(res => {
    
    
		if (res.code == 1) {
    
    
			this.$common.success(res.msg)
			setTimeout(()=>{
    
    
				this.$common.back()
			},1200)
		}
	})
},

New upload code: (multiple image processing)

<view class="imgBox">
	<u-upload :fileList="fileList" @afterRead="afterRead" @delete="deletePic" :multiple="true" :maxCount="9">
		<image :src="$common.image('/static/talentZone/addImg.png')" mode="aspectFill"  class="fileImg"></image>
	</u-upload>
</view>
data() {
    
    
	return {
    
    
		// 图片列表
		fileList: []
	}
},
methods: {
    
    
	// 图片上传
	//删除图片
	deletePic(e) {
    
    
		console.log(e);
		this.fileList.splice(e.index, 1)
	},
	// 新增图片
	async afterRead(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 result = await this.uploadFilePromise(lists[i].url)
			console.log(result);
			if(result.success){
    
    
				let item = this.fileList[fileListLen]
				this.fileList.splice(fileListLen, 1, Object.assign(item, {
    
    
					status: 'success',
					message: '',
					url: result
				}))
				fileListLen++
			}else{
    
    
				this.fileList.splice(fileListLen, 1)
			}
			
		}
	},
	//上传图片
	uploadFilePromise(url) {
    
    
		return new Promise((resolve, reject) => {
    
    
			let a = uni.uploadFile({
    
    
				url:'http://192.168.2.21:7001/upload', // 仅为示例,非真实的接口地址,换成自己上传图片的接口
				filePath: url,
				name: 'file',
				success: (uploadRes) => {
    
    
					setTimeout(()=>{
    
    
						let res = JSON.parse(uploadRes.data) //最终传给的是字符串,这里需要转换格式
						if(res.code == 0){
    
    
							this.$common.msg(res.msg)
							resolve({
    
    success:false,url:''})
							return;
						}
						resolve({
    
    success:true,url:res.data.url})
					},2000)
					
				}
			});
		})
	},
	//点击确认还需要些许修改
	fabu() {
    
    
		let images = []
		this.fileList.forEach((item) => {
    
    
			images.push(item.url.url)
		})
		// 其他接口
		request('post', '其他接口地址', {
    
    
			title: this.textValue,
			info: this.textValue,
			images: images.join(',')//重点是这里,需要看后台接收的类型进行更改
		}).then(res => {
    
    
			if (res.code == 1) {
    
    
				console.log(res);
			}
		})
	},
}

upload picture

// 图片上传
//删除图片
deletePic(event) {
    
    
	this[`fileList${
      
      event.name}`].splice(event.index, 1)
},
// 新增图片
async afterRead(event) {
    
    
	// 当设置 multiple 为 true 时, file 为数组格式,否则为对象格式
	let lists = [].concat(event.file)
	let fileListLen = this[`fileList${
      
      event.name}`].length
	lists.map((item) => {
    
    
		this[`fileList${
      
      event.name}`].push({
    
    
			...item,
			status: 'uploading',
			message: '上传中'
		})
	})
	for (let i = 0; i < lists.length; i++) {
    
    
		const result = await this.uploadFilePromise(lists[i].url)
		console.log("结果", result);
		if (result.success) {
    
    
			let item = this.fileList[fileListLen]
			this.fileList.splice(fileListLen, 1, Object.assign(item, {
    
    
				status: 'success',
				message: '',
				url: result
			}))
			fileListLen++
		} else {
    
    
			this.fileList.splice(fileListLen, 1)
		}
	}
},
uploadFilePromise(url) {
    
    
	return new Promise((resolve, reject) => {
    
    
		let a = uni.uploadFile({
    
    
			url: config[config.env].apiUrl + '/api/common/upload', // 仅为示例,非真实的接口地址
			filePath: url,
			name: 'file',
			formData: {
    
    
				user: 'test'
			},
			success: (uploadRes) => {
    
    
				setTimeout(() => {
    
    
					let res = JSON.parse(uploadRes.data) //最终传给的是字符串,这里需要转换格式
					if (res.code == 0) {
    
    
						this.$common.msg(res.msg)
						resolve({
    
    
							success: false,
							url: ''
						})
						return;
					}
					console.log("图片", res);
					resolve({
    
    
						success: true,
						url: res.data.url
					})
				}, 1000)
			}
		});
	})
},

Single image value transfer

data(){
    
    
	return{
    
    
		payment_credentials:''//支付凭证(线下必填)
	}
},
methods: {
    
    
aaa(){
    
    
	if (this.fileList.length > 0) {
    
    
		this.payment_credentials = this.fileList[0].url.url
	}}
	
}

Picture echo

When the content is modified, the last uploaded image needs to be displayed first (the image array will be returned in the background), and then some of the last images may be deleted, or some new images may be uploaded. The image array of the data finally submitted to the background does not have a domain name.
The overall steps are as follows:

data() {
    
    
	return {
    
    
		// 图片列表
		fileList: [],
		//修改功能 需要提交的图片数组
		subImg:[]
	}
},

1. Modify, query the information of this data based on the id, and return the data information in the background. Here we only talk about pictures. First, imagesit is processed, and the string is converted into an array. Then the divided array subImgis traversed and looped, and the image path (after splicing the domain name) is pushed into fileListthe array. At this time, the image of the page can be displayed.

this.subImg = res.data.images.split(',') //字符串转化为数组
this.subImg.forEach(item=>{
    
    
	console.log(item);
	this.fileList.push({
    
    
		url:  this.$common.image(item)//拼接好域名之后push进去
	})
})
console.log(this.fileList);

Insert image description here

2. Since the image array submitted to the background after modification does not have a domain name, an array is customized and the subImgfirst two images are assigned to it when it is first uploaded. If deleted, it will be deleted according to the deleted subscript. Delete the images in this array. Every time you upload a new image, push the image path returned after the new upload. In this way, whether you delete or add a new image, you can ensure that the images in the sunImg array are the latest and do not contain domain name

Core code:

this.subImg.splice(e.index, 1)
this.subImg.push(res.data.url)

Specific code:

//删除图片
deletePic(e) {
    
    
	console.log(e);
	this.fileList.splice(e.index, 1)
	this.subImg.splice(e.index, 1)  //新增删除代码
},
// 新增图片
async afterRead(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 result = await this.uploadFilePromise(lists[i].url)
		console.log(result);
		if (result.success) {
    
    
			let item = this.fileList[fileListLen]
			this.fileList.splice(fileListLen, 1, Object.assign(item, {
    
    
				status: 'success',
				message: '',
				url: result
			}))
			fileListLen++
		} else {
    
    
			this.fileList.splice(fileListLen, 1)
		}
	}
},
//上传图片
uploadFilePromise(url) {
    
    
	return new Promise((resolve, reject) => {
    
    
		let a = uni.uploadFile({
    
    
			url: config[config.env].apiUrl + '/api/common/upload',
			filePath: url,
			name: 'file',
			success: (uploadRes) => {
    
    
				setTimeout(() => {
    
    
					let res = JSON.parse(uploadRes.data) //最终传给的是字符串,这里需要转换格式
					if (res.code == 0) {
    
    
						this.$common.msg(res.msg)
						resolve({
    
    
							success: false,
							url: ''
						})
						return;
					}
					console.log("图片", res.data.url);
					this.subImg.push(res.data.url)  //新增添加代码
					resolve({
    
    
						success: true,
						url: res.data.url
					})
				}, 2000)
			}
		});
	})
},

Guess you like

Origin blog.csdn.net/xulihua_75/article/details/127206064#comments_27843925