uni+upload上传压缩图片

本文介绍了一个用于图片上传的封装组件,支持多种平台如H5和APP,并详细展示了如何实现图片压缩、预览及上传功能。

废话不多说,上代码
封装的一个js,里面内容为

export const upload = {
	afterRead(event, lists, filelist, fileListLen, url) {
		return new Promise((resolve, reject) => {
			lists.map((item) => {
				filelist.push({
					...item,
					status: 'uploading',
					message: '上传中'
				})
			})
			for (let i = 0; i < lists.length; i++) {
				// #ifdef APP  
				uni.compressImage({
					src: lists[i].url,
					quality: 80,
					success: async res => {
						console.log(res.tempFilePath)
						const result = await this.uploadFilePromise(res.tempFilePath, url)
						let item = filelist[fileListLen]
						filelist.splice(fileListLen, 1, Object.assign(item, {
							status: 'success',
							message: '',
							url: result
						}))
						fileListLen++
						resolve(result)
					}
				})
				// #endif  
				// #ifdef H5 
				console.log(lists[i].url)
				const img = new Image()
				console.log(img)
				img.src = lists[i].url // 指定图片的DataURL(图片的base64编码数据)
				let files = {};
				img.onload = async () => {
					const canvas = document.createElement('canvas') // 创建Canvas对象(画布)
					const context = canvas.getContext('2d')
					//默认按比例压缩
					let cw = img.width
					let ch = img.height
					let w = img.width
					let h = img.height
					canvas.width = w
					canvas.height = h
					if (cw > 600 && cw > ch) {
						w = 600
						h = (600 * ch) / cw
						canvas.width = w
						canvas.height = h
					}
					if (ch > 600 && ch > cw) {
						h = 600
						w = (600 * cw) / ch
						canvas.width = w
						canvas.height = h
					}
					// 生成canvas
					let base64 // 创建属性节点
					context.clearRect(0, 0, 0, w, h)
					context.drawImage(img, 0, 0, w, h)
					base64 = canvas.toDataURL(lists[i]['type'], 0.5)
					const result = await this.uploadFilePromise(base64, url)
					let item = filelist[fileListLen]
					filelist.splice(fileListLen, 1, Object.assign(item, {
						status: 'success',
						message: '',
						url: result
					}))
					fileListLen++
					resolve(result)
				}
				// #endif 
			}
		})
	},
	uploadFilePromise(filePath, url) {
		return new Promise((resolve, reject) => {
			uni.uploadFile({
				url: url,
				filePath: filePath,
				name: 'file',
				formData: {
					fileToUpload: 'test'
				},
				success: (res) => {
					if (res.data.indexOf("code") != -1) {
						console.log(JSON.parse(res.data))
						uni.showToast({
							title: JSON.parse(res.data).msg,
							icon: "error",
							duration: 2000
						})
						var fileList1 = []
					} else {
						// uni.showToast({
						// 	title: "上传成功",
						// 	icon: "success",
						// 	duration: 2000
						// })
						// setTimeout(() => {
						console.log(res.data)
						resolve(res)
						// }, 1000)
					}

				}
			});
		})
	}
}

在main.js里引入

import {upload} from './until/upload.js'
Vue.prototype.$upload = upload

在需要上传的页面使用

<template>
	<view>
		<view class="tit">
			当前头像
		</view>
		<view class="img">
			<image :src="face" mode=""></image>
		</view>
		<view class="tit">
			更换头像
		</view>
		<view class="pic">
			<u-upload :fileList="fileList1" @afterRead="afterReads" @delete="deletePic" name="1" multiple :maxCount="1">
			</u-upload>
		</view>
		<button type="default" @click="pic">提交</button>
	</view>
</template>

<script>
	export default {
		data() {
			return {
				bgColor: "#fd8b3c",
				value3: '',
				fileList1: [],
				face: "",
				pics: ""
			}
		},
		onLoad(callback) {
			this.yes()
		},
		methods: {
			async yes() {//获取当前头像
				var user_id = uni.getStorageSync("user_id")
				const res = await this.$myrequest({
					url: '/app/user/getUserInfo',
					method: 'POST',
					header: {
						'token': uni.getStorageSync("token"), //自定义请求头信息
					},
					data: {
						user_id: user_id,
					},
				})
				console.log(res)
				this.show = false
				if (res.data.code == 1) {
					console.log(res.data.data)
					this.face = res.data.data.face

				} else {
					uni.showToast({
						title: res.data.msg,
						icon: "error",
						duration: 2000
					})
				}
			},
			async pic() {//编辑更改头像
				console.log(this.pics)
				var user_id = uni.getStorageSync("user_id")
				const res = await this.$myrequest({
					url: '/app/user/editHeadImage',
					method: 'POST',
					header: {
						'token': uni.getStorageSync("token"), //自定义请求头信息
					},
					data: {
						user_id: user_id,
						head_img: this.pics
					},
				})
				if (res.data.code == 1) {
					uni.showToast({
						title: res.data.msg,
						icon: "success",
						duration: 2000
					})
					location.reload()
				} else {
					return uni.showToast({
						title: res.data.msg,
						icon: "error",
						duration: 2000
					})
				}

			},
			deletePic(event) {
				this[`fileList${event.name}`].splice(event.index, 1)
			},
			// 新增图片
			async afterReads(event) {
				let url = '/app/upload/upload/model/face'//示例上传图片接口地址
				let lists = [].concat(event.file)
				let fileListLen = this[`fileList${event.name}`].length
				let filelist = this[`fileList${event.name}`]
				var result = await this.$upload.afterRead(event, lists, filelist, fileListLen, url)
				this.pics = result.data
			}
		}
	}
</script>

<style lang="scss">
	.tit {
		height: 50px;
		line-height: 50px;
		margin-left: 5%;
	}

	.img {
		width: 64px;
		height: 64px;
		margin-left: 15%;

		image {
			width: 100%;
			height: 100%;
			border-radius: 50%;
		}
	}

	.pic {
		margin-left: 15%;
	}

	button {
		width: 80%;
		margin: 10% auto;
		background: #fd8b3c;
		color: white;
	}
</style>

完结,撒花!
有不完整的还请大佬指正~

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值