uniapp、uview——图片上传(单图上传、多图上传、多组照片上传、图片回显)

一、简介

uView组件的上传功能,单图上传、多图上传等。
官方文档地址:
https://www.uviewui.com/components/upload.html

二、步骤

(一)单图上传

1.效果演示:

只能上传一张,选完之后,上传的按钮消失,当然,如果图片不合适,删掉再换一张,但就是只能上传一张。
在这里插入图片描述

2.代码:
<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>

(二)多图上传

1.效果演示:

可一次性选多张,我这里限制为两张,上传满两张则不会显示上传的logo。点击图片可预览。
在这里插入图片描述

2.代码:
<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>

三、其余补充

在这里插入图片描述
如果一个页面上有多处上传,操作也不是很复杂,大家都是共用同一个方法。
在这里插入图片描述
整体搬过来用即可。
在这里插入图片描述
请求接口的地方需要用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)
		}
	})
},

新上传代码:(多图处理)

<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);
			}
		})
	},
}

图片上传

// 图片上传
//删除图片
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)
			}
		});
	})
},

单图传值

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

图片回显

当内容进行修改时,需要先将上次上传过的图片进行显示(后台会返回图片数组),之后或许删除上次中的某种图片,也有可能会新上传一些图片。最后提交给后台的数据的图片数组是不带域名的。
整体步骤如下:

data() {
	return {
		// 图片列表
		fileList: [],
		//修改功能 需要提交的图片数组
		subImg:[]
	}
},
1.修改,根据id 进行查询此条数据的信息,后台返回该条数据信息,这里只说图片的事。首先对images进行处理,字符串转化为数组,之后对分割后的数组subImg进行遍历循环,把图片路径(拼接好域名之后)push到fileList数组里面,这时候页面的图片就能显示了。
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);

在这里插入图片描述

2.由于修改之后提交给后台的图片数组是不带域名的,所以自定义了一个subImg数组,刚上来的时候就已经赋进去了最初始的两张图,如果删除,就根据删除的下标删除掉此数组里面的图片,每次上传新图片的时候,就把新上传后返回的图片路径push进去,这样 不管是删除还是新增都能保证sunImg数组里面的图片都是最新的,且不带域名

核心代码:

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

具体代码:

//删除图片
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)
			}
		});
	})
},
uniapp (微信小程序、H5等统一框架) 中,结合UView UI库,你可以实现上传照片并添加水印的功能,以下是基本步骤: 1. **安装依赖**: 首先,确保你已经在项目中安装了uni-app及其相应的UI组件库`uview-ui`。如果尚未安装,可以在项目目录下运行`npm install uview-ui` 或 `yarn add uview-ui`。 2. **引入组件**: 在需要的页面文件中,导入所需的`u-file-picker`(文件选择器)、`u-image`(图片展示)以及`u-watermark`(水印组件)。 ```javascript import { view, image, filePicker, waterMark } from 'uview-ui' ``` 3. **获取用户照片**: 使用`filePicker`让用户选择照片,然后读取图片数据: ```javascript const choosePhoto = async () => { const result = await filePicker({ type: ['image'], sizeLimit: 5 * 1024 * 1024 // 限制图片大小 }) if (!result.name) return // 图片路径或base64字符串 const imgData = result.tempFilePath || result.fileList[0].url } ``` 4. **添加水印**: 使用`waterMark`组件,在选择的照片上添加文字或图片作为水印。例如,将水印图片和文本插入到图片中: ```javascript const addWatermark = (src, watermarkSrc, text) => { // 创建一个新的canvas元素用于添加水印 const canvas = document.createElement('canvas') const ctx = canvas.getContext('2d') // 设置图片和水印 const img = new Image() img.src = src img.onload = function() { const width = img.width const height = img.height // 水印图片加载 const wmarkImg = new Image() wmarkImg.src = watermarkSrc wmarkImg.onload = function() { const wmarkWidth = wmarkImg.width const wmarkHeight = wmarkImg.height // 计算水印位置 let x = width - wmarkWidth let y = height - wmarkHeight // 绘制图片和水印 ctx.drawImage(img, 0, 0) ctx.drawImage(wmarkImg, x, y) // 添加文本水印 ctx.font = 'bold 14px Arial' ctx.fillStyle = '#000' // 黑色字体颜色 ctx.fillText(text, 10, height - 20) // 文本位置 // 将canvas转换为Base64 const base64Image = canvas.toDataURL() // 上传图片及水印图片至服务器 uploadWithWatermark(base64Image, watermarkSrc) } img.crossOrigin = 'Anonymous' } } // 上传带有水印的图片函数 async function uploadWithWatermark(imageStr, watermarkStr) { // 发送POST请求到服务器,附带上图片和水印数据 // 可以通过fetch, axios或其他HTTP库实现 } ``` 5. **调用组件和功能**: 在合适的界面点击事件中调用`choosePhoto()`和`addWatermark()`函数。 注意:上述示例是一个简化的流程,实际应用中还需要处理更细节,如错误处理、水印图片的加载优化以及服务器API的调用。同时,对于敏感操作,确保遵守相关的隐私政策,并保护用户数据安全。
评论 11
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值