失眠网,内容丰富有趣,生活中的好帮手!
失眠网 > vue移动端van-uploader上传图片压缩工具类

vue移动端van-uploader上传图片压缩工具类

时间:2018-11-10 14:44:35

相关推荐

vue移动端van-uploader上传图片压缩工具类

1、最近移动端项目中使用van-uploader上传图片,开发测试都正常,上线后苹果用户反馈图片上传不了,最后排查是图片过大导致调用上传接口后一直没有返回。

2、utils文件夹下新建imgCompressUtil.js文件:

3、工具类中的具体代码:

const imgCompressUtil = {compressImg (file) {let self = thisif (!file || !window.FileReader) return // 判断是否支持FileReaderif (/^image/.test(file.type)) {let reader = new FileReader()reader.readAsDataURL(file) // 转成 base64 格式return new Promise((resolve, reject) => { // 读取成功后的回调reader.onloadend = function () {let img = new Image()img.src = this.result// 判断图片是否大于500K,是就直接上传,反之压缩图片if (this.result.length <= 500 * 1024) {resolve(this.result)} else {img.onload = function () {let canvas = document.createElement('canvas')let ctx = canvas.getContext('2d')let tCanvas = document.createElement('canvas')let tctx = tCanvas.getContext('2d')let width = img.widthlet height = img.height// 如果图片大于四百万像素,计算压缩比并将大小压至400万以下let ratioif ((ratio = (width * height) / 4000000) > 1) {console.log('大于400万像素')ratio = Math.sqrt(ratio)width /= ratioheight /= ratio} else {ratio = 1}canvas.width = widthcanvas.height = heightctx.fillStyle = '#fff' // 铺底色ctx.fillRect(0, 0, canvas.width, canvas.height)// 如果图片像素大于100万则使用瓦片绘制let countif ((count = (width * height) / 1000000) > 1) {count = ~~(Math.sqrt(count) + 1) // 计算要分成多少块瓦片// 计算每块瓦片的宽和高let nw = ~~(width / count)let nh = ~~(height / count)tCanvas.width = nwtCanvas.height = nhfor (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)}// 进行压缩(---------quailty越低 图片越小)let quailty = 0.5let newBase64 = canvas.toDataURL('image/jpeg', quailty)tCanvas.width = tCanvas.height = canvas.width = canvas.height = 0resolve(newBase64) // 返回压缩后的base64}}}})}}}export default imgCompressUtil

4、van-uploader上传图片的内容如下,直接上传的话用content(base64),压缩的话压缩其中的file文件即可:

5、文件压缩:

async submit() {Toast.loading({duration: 0,forbidClick: true,message: "任务反馈中..."})let files = []for (let i = 0; i < this.fileList.length; i++) {await pressImg(this.fileList[i].file).then(res => {files.push(res)})}let params = {id: this.item.id,content: this.contentValue,files: files,meritId: this.item.meritsId,userId: this.userid}commonApi.feedback(params).then(res => {Toast.clear()if (res.code === '0') {Toast.success('任务反馈成功')this.$router.go(-1)} else {this.$message({ message: res.msg, type: 'warning', duration: 2000 })}})}

上面代码中fileList中便是上传的图片集合,压缩时要用async、await,压缩后再上传便正常了。

如果觉得《vue移动端van-uploader上传图片压缩工具类》对你有帮助,请点赞、收藏,并留下你的观点哦!

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