uniapp小程序图片前端压缩上传
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(),有惊喜哦
公众号
往期文章
- 助你上手Vue3全家桶之Vue-Router4教程
- 助你上手Vue3全家桶之Vue3教程
- 助你上手Vue3全家桶之VueX4教程
- 使用nvm管理node.js版本以及更换npm淘宝镜像源
- 超详细!Vue-Router手把手教程
- vue中利用.env文件存储全局环境变量,以及配置vue启动和打包命令
- 微信小程序实现搜索关键词高亮
- 超详细!Vue的九种通信方式
- 超详细!Vuex手把手教程
个人主页
uniapp小程序图片前端压缩上传的更多相关文章
- HTML5 图片本地压缩上传插件「localResizeIMG」
移动应用中用户往往需要上传照片,但是用户上传的照片尺寸通常很大,而手机的流量却很有限,所以在上传前对图像进行压缩是很有必要的. 原生应用可以直接对文件进行处理,网页应用就没有这个优势了.不过 canv ...
- CANVAS运用-对图片的压缩上传(仅针对移动浏览器)
最近在移动端设计头像上传功能时,原本是以<input type="file">直接通过formData上传,然而实际使用情况是:对于过大的图片(高像素手机所拍摄的照片等 ...
- 微信小程序:多张图片上传
最近在写小程序的相册,需要多张图片的上传.因为小程序不支持数组的多张图片同时上传,然后根据自己的需求+借鉴网上各位大神的案例,总算搞定.分享下,不足之处,多多指教哦 页面wxml: <form ...
- Day12-微信小程序实战-交友小程序-搭建服务器与上传文件到后端
要搞一个小型的cms内容发布系统 因为小程序上线之后,直接对数据库进行操作的话,慧出问题的,所以一般都会做一个管理系统,让工作人员通过这个管理系统来对这个数据库进行增删改查 微信小程序其实给我们提供了 ...
- 微信小程序入门八头像上传
1. action-sheet 底部弹出可选菜单组件 2. wx.uploadFile 将本地资源上传到服务器 3. wx.chooseImage 从本地相册选择图片或使用相机拍照. 4. wx.pr ...
- 微信小程序--更换用户头像/上传用户头像/更新用户头像
changeAvatar:function (){ var that=this; wx.chooseImage({ count: 1, // 默认9 sizeType: ['original', 'c ...
- 小程序图片在安卓上拉伸的问题&导航&返回首页
今天提了一个bug,有几张图片在安卓上面加载会先变大拉伸再恢复正常 出现这样的问题应该是用widthFix造成的 具体原因还不是很清楚,因为都是本地图片,所以我就直接把高也设置好就暂时没有这个问题 ...
- 前台图片Canvas压缩上传小结
需求来源:之前有个提交审核表单的业务,表单中含有大量附件图片,大约有20多张吧,为了省事,采用的同步上传,一次需要上传很多照片,本来单张图片限制为200KB,这样子总图片大小约为5MB左右,想想也可以 ...
- 微信小程序--图片相关问题合辑
图片上传相关文章 微信小程序多张图片上传功能 微信小程序开发(二)图片上传 微信小程序上传一或多张图片 微信小程序实现选择图片九宫格带预览 ETL:微信小程序之图片上传 微信小程序wx.preview ...
随机推荐
- WPF之复选MVVM TreeView(TreeView+CheckBox)
需求背景: 当我们用到权限菜单栏时权限菜单栏属于递归效果,我们需要用到TreeView+CheckBox进行组合复选开发时,我们需要解决此类问题时怎么办,那么就引出今天的小笔记内容 实现方式: 下载M ...
- Oracle数据库-常规中行显示0,解决方案
如图,如果当前位置显示为0 原因:Oracle不是实时的对表进行分析的,需要手动执行分析. 解决方案: 分析表 analyze table tablename compute statistics;
- Numpy的各种下标操作
技术背景 本文所使用的Numpy版本为:Version: 1.20.3.基于Python和C++开发的Numpy一般被认为是Python中最好的Matlab替代品,其中最常见的就是各种Numpy矩阵类 ...
- spring中容器和对象的创建流程
容器和对象的创建流程 1.先创建容器 2.加载配置文件,封装成BeanDefinition 3.调用执行BeanFactoryPostProcessor 准备工作: 准备BeanPostProcess ...
- embarrass的writeup
大家好,这次我要为大家带来都是攻防世界misc部分embarrass的writeup. 首先下载附件,是一个压缩包,解压后找到一个流量包.用wireshark打开,直接在搜索框中输入flag{ ...
- 案例五:shell脚本实现定时监控http服务的运行状态
注意:监控方法可以为端口.进程.URL模拟访问方式,或者三种方法综合. 说明:由于截止到目前仅讲了if语句,因此,就请大家用if语句来实现. [root@oldboy-B scripts]# cat ...
- 【C# .Net GC】条件自动垃圾回收 HandleCollector类
条件自动回收 达到指定条件后自动执行GC回收垃圾. GC中的方法AddMemoryPressure和RemoveMemoryPressure 本机资源有时会消耗大量内存,但用于包装它的托管对象只占用很 ...
- dbeaver安装配置
安装出现库依赖没有,可以添加maven仓库 修改字体:小四
- 小记:音频格式转化ByPython(下)
上文中我们已经大致明白了pydub库的使用方法,今天的目标是写个爬虫爬取歌曲信息. 关于网络爬虫,Python的标准库里是有相应的包的,可以直接打开:https://docs.python.org/z ...
- 【spring】事务底层的实现流程
事务简单介绍 本文源码基于spring-framework-5.3.10. 事务是基于AOP的机制进行实现的! Spring事务基本执行原理 一个Bean在执行Bean的创建生命周期时,会经过Infr ...