本文上传图片压缩采纳为https://www.jb51.net/article/156091.htm
首先,让我们来分析一下实现多图片上传的流程:
- 前端向后端请求用来上传图片至服务器的token
- 后端为每张要上传的图片生成一个图片名,并用这个图片名生成token
- 后端将图片名(前缀(域名))和token返回给前端
- 前端拿到token以后,将图片上传至七牛云
- 上传成功以后,七牛云返回图片的后缀参数
- 前端将图片前缀和后缀拼接成完整的url发给后端
- 后端将图片名存入数据库
<el-upload
action=""
list-type="picture-card" accept="image/jpeg,image/jpg,image/png"
:class="{hide:hideUpload}"
:on-change="imgChange"
:file-list="fileList"
ref="upload"
:on-preview="handlePictureCardPreview"
:before-upload="beforeAvatarUpload"
:on-remove="handleRemove" :limit="10" :on-exceed="handleExceed" :http-request="upqiniu">
<div style="margin-top: 29px;" class="name_upload">
<img src="../assets/add.png" alt="" style="width: 83px;"><br />
<p>最多上传十张</p>
</div>
</el-upload>
<el-dialog :visible.sync="dialogVisible" size="tiny">
<img width="100%" :src="dialogImageUrl" alt="">
</el-dialog>
data() {
return {
imgQuality: 0.8, //图片压缩质量
fileList:[],//存放于储存的图片
}
}
methods: {
upqiniu(file) {
//用于自定义上传
//这里我们先给后台发送请求拿到需要的token
console.log(file);
this.$axios.post("xxxx").then((response) => {
console.log(response);
if (response.data.code === 10000) {
//请求成功拿到的token
this.handleSuccessa(response.data, file.file, file);
} else {
this.$message({
message: `${response.data.message}`,
type: 'warning'
});
}
})
},
handleSuccessa(response, file, fileList) {
console.log(response);
console.log(file);
//在这里进行上传七牛云
// console.log(fileList);
var that = this;
var token = response.resultObject.token;
var key = file.name.split('.')[0] + new Date().getTime();
console.log(key);
var putExtra = {
fname: "",
params: {},
mimeType: [] || null
};
console.log(putExtra);
var config = {
useCdnDomain: true,
disableStatisticsReport: false,
retryCount: 6,
region: qiniu.region.z2
};
console.log(config);
console.log(qiniu);
// var observable = qiniu.upload(file.raw, key, token, putExtra, config);
var observable = qiniu.upload(file, key, token, putExtra, config);
var observer = {};
observer = {
next(res) {
console.log(res);
// fileList.onProgress(res.total.percent);
//这里是做上传图片的上传进度
fileList.onProgress(res.total);
if (res.total.percent == 100) {
// alert("图片上传成功")
that.$notify({
title: '成功',
message: '图片上传成功',
type: 'success'
});
};
},
error(err) {},
complete(res) {
//我们的前缀是固定不变的,所以我直接写死了
that.fileList.push({
url: `http://xxxxx/${res.key}`,
uid: file.uid,
name: file.name
});
console.log(res);
}
};
//上传到七牛云
var subscription = observable.subscribe(observer)
},
}
这里是压缩处理
beforeAvatarUpload(param) {
console.log(param);
const imgSize = param.size / 1024 / 1024;
console.log(imgSize);
//这里做图片的压缩 如果大于1M我们进行等比压缩处理
if (imgSize > 1) {
const _this = 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');
const width = image.width * _this.imgQuality
const height = image.height * _this.imgQuality
canvas.width = width;
canvas.height = height;
context.clearRect(0, 0, width, height);
context.drawImage(image, 0, 0, width, height);
const dataUrl = canvas.toDataURL(param.type);
const blobData = _this.dataURItoBlob(dataUrl, param.type);
console.log(blobData);
resolve(blobData)
}
reader.onload = (e => {
image.src = e.target.result;
});
reader.readAsDataURL(param);
})
}
},
dataURItoBlob(dataURI, type) {
console.log(dataURI, 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
});
},
压缩图片实现起来比较简单。就是在beforeUpload()方法里面return一个Promise,Promise里面我们把图片的长度和宽度按比例进行缩小,并把图片画到canvas上,然后把canvas转成一个blod对象。
当我点击上传按钮的时候
submit() {
let picUrls = [];
const _this = this;
//这里就为我们的图片集合
//每个包含,我们只是需要url
// {
// name:"图片的名字",
// url:"图片的地址",
// uid:"element 给生成的id删除的时候会用到"
// }
this.fileList.map((item) => {
picUrls.push(item.url)
});
//图片集合
console.log(picUrls);
this.$axios.post("xxxxx", {
picUrls: picUrls.join(), //图片
dealPattern: this.dealPattern,
}).then((response) => {
if (response.data.code == 10000) {
console.log(response);
this.$message({
message: '成功',
type: 'success'
});
} else {
this.$message({
message: `${response.data.message}`,
type: 'warning'
});
}
})
},
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。