失眠网,内容丰富有趣,生活中的好帮手!
失眠网 > vant vue 图片上传压缩

vant vue 图片上传压缩

时间:2024-05-11 14:57:21

相关推荐

vant  vue 图片上传压缩

问题:解决vant图片上传太大 需要进行压缩 (PS: 我写了几个方法,这里我贴出主要得代码 用//*** ***标识 为重点)

1.图片压缩得方法

/*** 压缩图片方法* @param base64 ----baser64文件* @param scale ----压缩比例 画面质量0-9,数字越小文件越小画质越差*/compressImg (base64, scale) {let that = this// 处理缩放,转换格式// 下面的注释就不写了,就是new 一个图片,用canvas来压缩const img = new Image()let blobimg.src = base64const canvas = document.createElement('canvas')const ctx = canvas.getContext('2d')canvas.setAttribute('width', img.width + '')canvas.setAttribute('height', img.height + '')ctx.clearRect(0, 0, canvas.width, canvas.height)ctx.drawImage(img, 0, 0, canvas.width, canvas.height)// 转成base64 文件let imgType = base64.split(';')[0].split(':')[1]base64 = canvas.toDataURL(imgType)while (base64.length > that.maxSize) {scale -= 0.01 // *** 每次压缩减少的比例为0.01 ***base64 = canvas.toDataURL(imgType, scale)/*** 核心代码通过canvas去压缩 ***}// baser64 TO blobconst arr = base64.split(',')const bytes = atob(arr[1])const bytesLength = bytes.lengthconst u8arr = new Uint8Array(bytesLength)for (let i = 0; i < bytes.length; i++) {u8arr[i] = bytes.charCodeAt(i)}blob = new Blob([u8arr], {type: imgType})return blob},

2. 文件上传

updatePics (files) {let that = thislet fileArray = []if (files instanceof Array) { // 兼容单个图片fileArray = files} else {fileArray.push(files)}this.filesShow.push(...fileArray) // 数组拼接let params = new FormData() // 创建form对象for (let i = 0; i < fileArray.length; i++) {let fileObj = fileArray[i].fileif (fileObj.size > that.maxSize) { //*** 这边我设置得是 maxSize 为1024*1024*1 :1M ***let File = pressImg(fileArray[i].content, that.scale)params.append('file', File, fileObj.name) // *** 这边可以设置文件名称或者格式 ***} else {params.append('file', fileObj) // 表单提交多个file}}this.$http({url: this.$http.adornUrl('/sys/file/uploadFile'),method: 'post',data: params}).then(({data}) => {if (data && data.code === 0) {this.fileIds.push(...data.data.fileIds)this.filePaths.push(...data.data.filePaths)} else {this.$toast(data.msg)}})}

如果觉得《vant vue 图片上传压缩》对你有帮助,请点赞、收藏,并留下你的观点哦!

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。