1,前言

这次项目中做了一个图片上传,要求是大于2MB的就压缩成2MB一下的再上传,我这边利用了uniapp的文件接口,使用canvas做了一个压缩上传的功能,目前已上线,使用无问题。

2,实现代码


定义canvas

<canvas canvas-id="imgCanvas" class="imgCanvas" />

canvas样式

.imgCanvas{
position: absolute;
top: -100%;
width: 100%;
height: 100%;
}

定义数据

// 引入图片压缩的方法
import { imgCompress } from '../../utils/index.js'
// 定义2MB
const Limit = 1024 * 1024 * 2
// 页面数据
data() {
return {
imgsPath: [], // 图片路径ID
imgsUrl: [] // 查看大图
}
}

打开相册

// 打开相册
handleOpenPhoto() {
const _this = this
uni.chooseImage({
success: (chooseImageRes) => {
const imgPaths = chooseImageRes.tempFiles
const successUp = 0 // 成功计数
const failUp = 0 // 失败计数
const count = 0 // 第几张
const total = imgPaths.length // 当前已上传个数
// 调用上传方法
_this.recursionUploading(imgPaths, successUp, failUp, count, total)
},
fail: (error) => {
console.warn(error)
}
})
}

递归上传

/**
* 递归上传
* @param {String} imgPaths 上传的图片地址
* @param {String} successUp 成功个数
* @param {String} failUp 失败个数
* @param {String} count 当前第几张
* @param {String} total 总数
*/
async recursionUploading(imgPaths, successUp, failUp, count, total) {
const _this = this
Loading.hide()
Loading.show(`上传第${count + 1}张...`)
let initPath = imgPaths[count].path
// 如果超过2MB就压缩
if (imgPaths[count].size > Limit) {
Loading.hide()
Loading.show(`第${count + 1}张压缩中...`)
initPath = await imgCompress.getCompressImage(imgPaths[count], 2)
}
uni.uploadFile({
header: {
'content-type': 'multipart/form-data',
'channel': '3',
'token': app.globalData.user.userToken
},
url: `${app.globalData.baseURL}/oss/uploadFile`,
filePath: initPath,
name: 'file',
formData: {
segmentId: 'WKDPE'
},
success: (uploadFileRes) => {
const res = JSON.parse(uploadFileRes.data)
if (res.code === '00000') {
_this.imgsPath.push({
path: imgPaths[count].path,
fileId: res.data.fileId
})
_this.imgsUrl.push(imgPaths[count].path)
successUp++ // 成功+1
} else {
failUp++
}
},
fail(e) {
failUp++ // 失败+1
},
complete(res) {
const data = JSON.parse(res.data)
if (data.code === '99990') {
uni.removeStorageSync('userInfo')
uni.removeStorageSync('user')
app.globalData.user = {}
app.globalData.userInfo = {}
Toast(data.message)
setTimeout(() => {
uni.reLaunch({
url: '../login/index'
})
}, 1000)
return
}
count++ // 下一张
if (count == total) {
Toast(`上传结束,总共${count}张,失败${failUp}张 !`)
} else {
// 递归调用,上传下一张
_this.recursionUploading(imgPaths, successUp, failUp, count, total);
}
}
})
}

删除照片

/**
* 删除照片
* @param {String} id 图片id
*/
deleteImg(id) {
const index = this.imgsPath.findIndex(item => {
return item.fileId === id
})
this.imgsPath.splice(index, 1)
}

预览大图

/**
* 预览大图
* @param {String} url 图片地址
* @param {String} index 当前图片下标
*/
handlePreviewImage(url, index) {
const _this = this
uni.previewImage({
urls: _this.imgsUrl,
current: index,
longPressActions: {
itemList: ['发送给朋友', '保存图片'],
success: function(data) {
console.log('选中了第' + (data.tapIndex + 1) + '个按钮,第' + (data.index + 1) + '张图片')
},
fail: function(err) {
console.log(err.errMsg)
}
}
})
}

压缩图片

/**
* 压缩图片
* @param {Object} file { path: '', size: '' }
* @param {Number} limitSize 压缩目标 MB
*/
export const imgCompress = {
MB: 1024 * 1024,
canvasId: 'imgCanvas',
ctx: uni.createCanvasContext('imgCanvas'),
// 获取可使用窗口宽度(提前使用uni.getSystemInfo获取windowWidth存在globalData)
rpxToPx(number) {
return number / 750 * getApp().globalData.systemInfo.windowWidth
},
// 获取文件信息
getFileInfo(path) {
return new Promise((resolve, reject) => {
uni.getFileInfo({
filePath: path,
success: (res) => {
console.log('File Size =>', `${res.size / this.MB}MB`)
resolve(res.size)
},
fail: () => reject(null)
})
})
},
// 获取图片信息
getImageInfo(path) {
return new Promise((resolve, reject) => {
uni.getImageInfo({
src: path,
success: (res) => resolve(res),
fail: () => reject(null)
})
})
},
// 判断是否达到压缩目标
getCompressImage(file, limitSize) {
if (file.size > this.MB * limitSize) {
return this.calcImaeg(file.path, limitSize);
} else {
return file.url
}
},
// 递归
async calcImaeg(url, limitSize) {
const size = await this.getFileInfo(url)
if (size > this.MB * limitSize) {
const imageInfo = await this.getImageInfo(url)
var maxSide = Math.max(imageInfo.width, imageInfo.height);
var windowW = this.rpxToPx(750)
var scale = 1
if (maxSide > windowW) {
scale = windowW / maxSide;
}
var imageW = Math.floor(imageInfo.width * scale)
var imageH = Math.floor(imageInfo.height * scale)
const newPath = await this.getCanvasImage(url, imageW, imageH)
return this.calcImaeg(newPath, limitSize)
} else {
return url
}
},
// 绘画
getCanvasImage(imagePath, imageW, imageH) {
return new Promise((resolve, reject) => {
this.ctx.drawImage(imagePath, 0, 0, imageW, imageH)
this.ctx.draw(false, () => {
uni.canvasToTempFilePath({
canvasId: this.canvasId,
x: 0,
y: 0,
width: imageW,
height: imageH,
quality: 1,
success: (res) => resolve(res.tempFilePath),
fail: () => reject(imagePath)
})
})
})
}
}

如果看了觉得有帮助的,我是@鹏多多,欢迎 点赞 关注 评论;END


PS:在本页按F12,在console中输入document.querySelectorAll('.diggit')[0].click(),有惊喜哦


公众号

往期文章

个人主页

uniapp小程序图片前端压缩上传的更多相关文章

  1. HTML5 图片本地压缩上传插件「localResizeIMG」

    移动应用中用户往往需要上传照片,但是用户上传的照片尺寸通常很大,而手机的流量却很有限,所以在上传前对图像进行压缩是很有必要的. 原生应用可以直接对文件进行处理,网页应用就没有这个优势了.不过 canv ...

  2. CANVAS运用-对图片的压缩上传(仅针对移动浏览器)

    最近在移动端设计头像上传功能时,原本是以<input type="file">直接通过formData上传,然而实际使用情况是:对于过大的图片(高像素手机所拍摄的照片等 ...

  3. 微信小程序:多张图片上传

    最近在写小程序的相册,需要多张图片的上传.因为小程序不支持数组的多张图片同时上传,然后根据自己的需求+借鉴网上各位大神的案例,总算搞定.分享下,不足之处,多多指教哦 页面wxml: <form ...

  4. Day12-微信小程序实战-交友小程序-搭建服务器与上传文件到后端

    要搞一个小型的cms内容发布系统 因为小程序上线之后,直接对数据库进行操作的话,慧出问题的,所以一般都会做一个管理系统,让工作人员通过这个管理系统来对这个数据库进行增删改查 微信小程序其实给我们提供了 ...

  5. 微信小程序入门八头像上传

    1. action-sheet 底部弹出可选菜单组件 2. wx.uploadFile 将本地资源上传到服务器 3. wx.chooseImage 从本地相册选择图片或使用相机拍照. 4. wx.pr ...

  6. 微信小程序--更换用户头像/上传用户头像/更新用户头像

    changeAvatar:function (){ var that=this; wx.chooseImage({ count: 1, // 默认9 sizeType: ['original', 'c ...

  7. 小程序图片在安卓上拉伸的问题&导航&返回首页

      今天提了一个bug,有几张图片在安卓上面加载会先变大拉伸再恢复正常 出现这样的问题应该是用widthFix造成的 具体原因还不是很清楚,因为都是本地图片,所以我就直接把高也设置好就暂时没有这个问题 ...

  8. 前台图片Canvas压缩上传小结

    需求来源:之前有个提交审核表单的业务,表单中含有大量附件图片,大约有20多张吧,为了省事,采用的同步上传,一次需要上传很多照片,本来单张图片限制为200KB,这样子总图片大小约为5MB左右,想想也可以 ...

  9. 微信小程序--图片相关问题合辑

    图片上传相关文章 微信小程序多张图片上传功能 微信小程序开发(二)图片上传 微信小程序上传一或多张图片 微信小程序实现选择图片九宫格带预览 ETL:微信小程序之图片上传 微信小程序wx.preview ...

随机推荐

  1. python中函数isinstance()用来判断某个实例是否属于某个类

    1 print(isinstance(1,int)) # 运行结果 True 2 # 判断1是否为整数类的实例 3 print(isinstance(1,str)) # 运行结果 False4 # 判 ...

  2. HttpClient的使用(get、post请求)

    添加pom依赖 <!-- https://mvnrepository.com/artifact/org.apache.httpcomponents/httpclient --> <d ...

  3. k8s虚拟机未关闭,电脑重启后,虚拟机无法启动

    莫名其妙电脑重启了,虚拟机连不上,心里真的是一万匹草泥马,显示如下: Generating "/run/initramfs/rdsosreport.txt" Entering em ...

  4. Mac欺骗实验

    实验目的 1.掌握MAC欺骗的原理 2.学会利用MacMakeUp软件工具进行伪造源MAC地址的MAC欺骗. 实验内容 使用MacMakeUp伪造主机mac地址,进行mac欺骗实验. 实验环境描述 1 ...

  5. 知识增广的预训练语言模型K-BERT:将知识图谱作为训练语料

    原创作者 | 杨健 论文标题: K-BERT: Enabling Language Representation with Knowledge Graph 收录会议: AAAI 论文链接: https ...

  6. vim编辑以及脚本编程练习

    转至:http://www.178linux.com/88128 vim编辑器的使用总结: vim在工作过程当中有三种模式:编辑模式.输入模式.末行模式. 1.编辑模式:即命令模式,键盘操作常被理解为 ...

  7. 在shell中变量的赋值有五种方法!

    转至:https://blog.csdn.net/weibo1230123/article/details/82085226 在shell中变量的赋值有五种 :使用 read 命令,直接赋值,使用命令 ...

  8. k8s全方位监控中-常用rules配置

    [root@VM_0_48_centos prometheus]# cat alertmanager-configmap.yaml apiVersion: v1 kind: ConfigMap met ...

  9. Python简单入门心得(一)

    很久之前就对Python感兴趣了,但是一直没时间学习,最近两天还有点时间,于是网上看了下视频,Python不愧是强类型的编程语言,对每一行的缩进的都有很严格的要求,比如一个判断,如果条件语句else不 ...

  10. linux下的硬盘分区、格式化、挂载

    linux下的MBR(msdos)分区.格式化.挂载 在linux下,需要使用一块硬盘. 需要进行以下四步: 识别硬盘-----分区规划-----格式化-----挂载 步骤一:分区规划 MBR模式分区 ...