Vue+ElementUI图片上传前进行图片压缩
图片上传使用的是ElementUI的Upload上传组件,参数说明请查看官网
页面使用组件
<el-upload :action="upload_path" list-type="picture-card" :data="upload_info" name="file" :on-success="uploadSuccess" :on-preview="handlePictureCardPreview" :on-remove="handleRemove" :before-upload="beforeAvatarUpload" :file-list="imgs" :show-file-list="true" accept="image/*"> <i class="el-icon-plus" /> </el-upload>
参数定义
data() { return { imgs: [], // 图片预览 dialogImageUrl: '', dialogVisible: false, upload_path: '图片上传api接口', // 上传时附带的额外参数 upload_info: { type: 'img', data: '上传时附带的额外参数' }, quality: 0.6, // 压缩比例 } },
Upload组件调用的方法:
methods: { // 文件上传成功 uploadSuccess(res) { if (res.code === 200) { this.imgs.push({ name: res.data, url: this.$fileUrl_ + '/' + res.data, path: res.data }) } else { console.error('文件上传失败', res.msg) } }, // 上传文件之前 beforeAvatarUpload(file) { // 图片大小大于2M进行图片压缩 if (file.size / 1024 / 1024 > 2) { const that = this return new Promise(resolve => { const reader = new FileReader() const image = new Image() image.onload = (imageEvent) => { const canvas = document.createElement('canvas') // 创建画布 const context = canvas.getContext('2d') // 画布为2d const width = image.width * that.quality // 图片宽度 * 压缩比例 const height = image.height * that.quality // 图片高度 * 压缩比例 canvas.width = width // 画布宽度 canvas.height = height // 画布宽度 context.clearRect(0, 0, width, height) context.drawImage(image, 0, 0, width, height) const dataUrl = canvas.toDataURL(file.type) //图片转路径 const blobData = that.dataURLtoBlob(dataUrl, file.type) //图片转二进制 resolve(blobData) } reader.onload = e => { image.src = e.target.result } reader.readAsDataURL(file) }) } else { return true } }, //图片转二进制 dataURLtoBlob(dataURL, type) { var binary = atob(dataURI.split(',')[1]) var array = [] for (var i = 0; i < binary.length; i++) { array.push(binary.charCodeAt(i)) } return new Blob([new Uint8Array(array)], { type: type }) }, // 图片移除 handleRemove(file, fileList) { const arr = [] fileList.forEach(r => { arr.push(r.response.data) }) this.imgs = arr }, // 图片预览 handlePictureCardPreview(file) { this.dialogImageUrl = file.url this.dialogVisible = true }, }