Vue2 | Vant uploader实现上传文件和图片

需求:

实现图片和文件的上传,单个图片超过1M则压缩,全部文件加起来不得超过10M。

效果:

1. html

<van-form ref="form">
 <van-field name="uploader" label="佐证材料" required>
	<template #input>
		<van-uploader
			v-model="files"
			multiple
			accept=""
			:before-read="beforeRead"
			:after-read="afterRead"
			@delete="deleteImg"
		/>
	</template>
 </van-field>
</van-form>

2. js:

    data() {
        return {
            files: [],
            fileList: [], // 已上传的图片
			fileIds: [], // 佐证材料文件id,上传成功之后返回的数据
			uploadfile: {
				type: '',
				name: ''
			}, // 上传单图的情况
			uploadfiles: [], // 上传多图的情况
        }
    },
    methods: {
        // 文件读取前触发
		beforeRead(e) {
			if (e.size > 10 * 1024 * 1024) {
				this.$toast.fail('文件大小不能超过10M')
				return false
			}
			return true
		},
		// 文件读取完成后触发
		afterRead(file) {
			if (file.length > 0) {
				// 多个上传
				file.map((item, index) => {
					this.uploadfiles.push({
						name: item.file.name,
						type: item.file.type
					})
					this.files[index].status = 'uploading'
					this.files[index].message = '上传中...'
					this.imgPreview(file[index].file, index)
				})
			} else {
				// 单个上传
				this.uploadfile.name = file.file.name // 获取文件名
				this.uploadfile.type = file.file.type // 获取类型
				this.files[this.files.length - 1].status = 'uploading'
				this.files[this.files.length - 1].message = '上传中...'
				// console.log('绑定的文件', this.files)
				this.imgPreview(file.file)
			}
		},
		// 删除文件
		deleteImg(file) {
			// 匹配fileList的项的fileName,相同的话把filesId对应删除
			this.fileList.map((item, index) => {
				if (item.file.name == file.file.name) {
					this.fileList.splice(index, 1)
					this.fileIds.splice(index, 1)
				}
			})
		},
		// 处理文件
		async imgPreview(file, index) {
			const self = this
			// 看支持不支持FileReader
			if (!file || !window.FileReader) return
			if (/^image/.test(file.type)) {
				// 创建一个reader
				const reader = new FileReader()
				// 将图片转成 base64 格式
				reader.readAsDataURL(file)
				// 读取成功后的回调
				reader.onloadend = function () {
					const result = this.result
					const img = new Image()
					img.src = result
					// 判断图片是否小于1M,是就直接上传,反之压缩图片
					if (this.result.length <= 1024 * 1024) {
						// 上传图片
						self.postImg(this.result, index)
					} else {
						img.onload = function () {
							const data = self.compress(img)
							// 上传图片
							self.postImg(data, index)
						}
					}
				}
			} else {
				// 其他格式的文件
				const formData = new window.FormData()
				formData.append('file', file)
				// 计算现在所有图片的大小,如果加上该文件超过10M则不可上传
				let totalSize = 0
				this.fileList.map(item => {
					totalSize += Number(item.file.size)
				})
				let size = totalSize + file.size
				if (size > 10 * 1024 * 1024) {
					this.$toast.fail('当前上传附件超过最大内存10M!')
					return
				}
				const res = await businessUpload(formData)
				if (res.code === 200) {
					this.$toast.success('文件已上传')
					this.fileIds.push(res.fileId)
					this.fileList.push({
						id: res.fileId,
						file: file
					})
					if (index == undefined) {
						this.files[this.files.length - 1].status = 'done'
						this.files[this.files.length - 1].message = '上传成功'
					} else {
						this.files[index].status = 'done'
						this.files[index].message = '上传成功'
					}
				} else {
					this.$toast.fail('文件上传失败')
					if (index == undefined) {
						this.files[this.files.length - 1].status = 'failed'
						this.files[this.files.length - 1].message = '上传失败'
					} else {
						this.files[index].status = 'failed'
						this.files[index].message = '上传失败'
					}
				}
			}
		},
		// 压缩图片
		compress(img, Orientation) {
			const canvas = document.createElement('canvas')
			const ctx = canvas.getContext('2d')
			// 瓦片canvas
			const tCanvas = document.createElement('canvas')
			const tctx = tCanvas.getContext('2d')
			// let initSize = img.src.length;
			let width = img.width
			let height = img.height
			// 如果图片大于四百万像素,计算压缩比并将大小压至400万以下
			let ratio
			if ((ratio = (width * height) / 4000000) > 1) {
				// console.log("大于400万像素");
				ratio = Math.sqrt(ratio)
				width /= ratio
				height /= ratio
			} else {
				ratio = 1
			}
			canvas.width = width
			canvas.height = height
			// 铺底色
			ctx.fillStyle = '#fff'
			ctx.fillRect(0, 0, canvas.width, canvas.height)
			// 如果图片像素大于100万则使用瓦片绘制
			let count
			if ((count = (width * height) / 1000000) > 1) {
				// console.log("超过100W像素");
				count = ~~(Math.sqrt(count) + 1) // 计算要分成多少块瓦片
				// 计算每块瓦片的宽和高
				const nw = ~~(width / count)
				const nh = ~~(height / count)
				tCanvas.width = nw
				tCanvas.height = nh
				for (let i = 0; i < count; i++) {
					for (let j = 0; j < count; j++) {
						tctx.drawImage(img, i * nw * ratio, j * nh * ratio, nw * ratio, nh * ratio, 0, 0, nw, nh)
						ctx.drawImage(tCanvas, i * nw, j * nh, nw, nh)
					}
				}
			} else {
				ctx.drawImage(img, 0, 0, width, height)
			}
			// 进行最小压缩
			const ndata = canvas.toDataURL('image/jpeg', 0.4)
			tCanvas.width = tCanvas.height = canvas.width = canvas.height = 0
			return ndata
		},
		// 提交图片到后端
		async postImg(base64, index) {
			const file = this.dataURLtoFile(base64, index)
			const formData = new window.FormData()
			formData.append('file', file)

			// 计算现在所有图片的大小,如果加上该文件超过10M则不可上传
			let totalSize = 0
			this.fileList.map(item => {
				totalSize += Number(item.file.size)
			})
			let size = totalSize + file.size
			if (size > 10 * 1024 * 1024) {
				this.$toast.fail('当前上传附件超过最大内存10M!')
				return
			}
			const res = await businessUpload(formData)
			if (res.code === 200) {
				this.$toast.success('图片已上传')
				this.fileIds.push(res.fileId)
				this.fileList.push({
					id: res.fileId,
					file: file
				})
				if (index == undefined) {
					this.files[this.files.length - 1].status = 'done'
					this.files[this.files.length - 1].message = '上传成功'
				} else {
					this.files[index].status = 'done'
					this.files[index].message = '上传成功'
				}
			} else {
				this.$toast.fail('图片上传失败')
				if (index == undefined) {
					this.files[this.files.length - 1].status = 'failed'
					this.files[this.files.length - 1].message = '上传失败'
				} else {
					this.files[index].status = 'failed'
					this.files[index].message = '上传失败'
				}
			}
		},
		// 将base64转换为文件
		dataURLtoFile(dataurl, index) {
			var arr = dataurl.split(',')
			var bstr = atob(arr[1])
			var n = bstr.length
			var u8arr = new Uint8Array(n)
			while (n--) {
				u8arr[n] = bstr.charCodeAt(n)
			}
			if (index == undefined) {
				// 单图上传
				return new File([u8arr], this.uploadfile.name, {
					type: this.uploadfile.type
				})
			} else {
				// 多图上传
				return new File([u8arr], this.uploadfiles[index].name, {
					type: this.uploadfiles[index].type
				})
			}
		}
    }

  • 3
    点赞
  • 22
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
移动端Vue VantUploader组件可以很方便地实现上传、压缩和旋转图片功能。首先,我们需要在Vue项目中引入Vue Vant库,并在需要使用Uploader的组件中注册该组件。 在页面中使用Uploader组件时,我们可以设置相关的属性来实现功能需求。首先是上传图片功能,可以通过设置`action`属性来指定图片上传的后端接口地址。上传成功后,可以通过监听`@success`事件来处理上传成功的逻辑,例如显示上传成功的提示信息或者将上传成功的图片URL保存到数据库等。 对于压缩图片的功能,我们可以使用该组件提供的`beforeRead`方法来获取用户要上传的图片文件对象。然后,利用`HTMLCanvasElement`的`toBlob`方法对图片进行压缩,并将压缩后的图片对象传给Uploader组件进行上传。在压缩图片时,可以设置压缩的尺寸或者压缩的质量、压缩比等参数,以控制压缩后的图片大小适应实际需求。 要实现图片旋转的功能,我们可以利用`EXIF.js`库来读取图片的EXIF信息,获取图片的拍摄方向。然后,根据拍摄方向来确定图片需要旋转的角度,再借助`canvas`的`rotate`方法对图片进行旋转。旋转后的图片可以在`@success`事件触发后重新渲染到页面上,或者直接发送到后端进行保存。 总结来说,移动端Vue VantUploader组件通过设置相关属性和监听事件,配合压缩工具和EXIF库,可以非常方便地实现图片上传、压缩和旋转功能,满足移动端图片处理的需求。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值