准备工作:
说明:
1.我们需求是图片宽度超过600像素的, 压缩到宽度600像素, 低于600像素的不做处理, 所以需要在上传前计算图片宽度.
2.具体的压缩参数请去github上看一下, 有帮助的话也star一下作者吧.
代码片段:
0.引包
import Compressor from 'compressorjs'
import * as qiniu from 'qiniu-js'
1.element upload组件
qiniuToken:从后台拿七牛上传token
我们需要自定义上传行为使用http-request, http-request会覆盖掉默认action
<el-upload
action="http://upload-z2.qiniup.com"
:data="{token:qiniuToken}"
:http-request="customUpload"
list-type="picture-card"
:disabled="false"
:before-upload="beforeUpload"
:show-file-list="false"
>
2.beforeUpload方法
beforeUpload(file) {
const isJPG = (file.type === 'image/jpeg') || (file.type === 'image/png')
const isLt5M = file.size / 1024 / 1024 < 5
if (!isJPG) {
this.$message.error('上传图片只能是 JPG/PNG 格式!')
}
if (!isLt5M) {
this.$message.error('上传图片大小不能超过 5MB!')
}
// 获取图片宽度
const _URL = window.URL || window.webkitURL
const img = new Image()
img.onload = function() {
this.imgWidth = img.width
}
img.src = _URL.createObjectURL(file)
return isJPG && isLt5M
},
3.customUpload方法
customUpload(file) {
const _this = this
// 尺度大于600像素,进行压缩
new Compressor(file.file, {
quality: this.imgWidth > 600 ? 0.8 : 1,
maxWidth: 500,
success(compressFile) {
// 七牛上传
const config = {
useCdnDomain: true, // 表示是否使用 cdn 加速域名,为布尔值,true 表示使用,默认为 false。
region: null // 根据具体提示修改上传地区,当为 null 或 undefined 时,自动分析上传域名区域
}
const putExtra = {
fname: '', // 文件原文件名
params: {}, // 用来放置自定义变量
mimeType: null // 用来限制上传文件类型,为 null 时表示不对文件类型限制;限制类型放到数组里: ["image/png", "image/jpeg", "image/gif"]
}
const observable = qiniu.upload(compressFile, null, file.data.token, putExtra, config)
observable.subscribe({
error: (err) => {
// 失败报错信息
console.log(err)
},
complete: (res) => {
//这里会返回成功后的key, 逻辑需要自己处理
_this.temp.listPic = _this.qiniuPre + res.key
}
})
},
error(err) {
console.log(err.message)
}
})
},