图片压缩后上传
html部分
// 上传图片
<div class="fileBox">
<span class="fileinput-button">
<div class="file_plus">
<i class="iconfont icon-zhaoxiangji" />
</div>
<input
type="file"
ref="selectFile"
accept="image/*"
style="width: 100px; height: 90px"
@change="getFileOthers($event, index)"
/>
</span>
</div>
js部分
// vue中data的数据
data() {
// 图片路径
fileList: [[]],
account: 0,
}
// js 部分
// 上传图片方法
getFileOthers(e, index) {
let _this = this;
_this.account = index;
var files = e.target.files[0];
// 转化为文件对象
let formData = new FormData();
if (!e || !window.FileReader) return; // 看支持不支持FileReader
let reader = new FileReader();
reader.readAsDataURL(files); // 将读取到的文件编码成DataURL
// 压缩图片
reader.onload = function(ev) {
try {
// 读取图片来获得上传图片的宽高
let img = new Image();
img.src = ev.target.result;
img.onload = function(ev) {
// 将图片绘制到canvas画布上进行压缩
let canvas = document.createElement("canvas");
let context = canvas.getContext("2d");
let imgWidth = img.width;
let imgHeight = img.height;
// 按比例缩放后图片宽高;
let targetWidth = imgWidth;
let targetHeight = imgHeight;
// /如果原图宽大于最大宽度
if (targetWidth > targetHeight) {
let scale = targetHeight / 1280; //原图宽高比例
targetHeight = 1280;
targetWidth = targetWidth / scale;
console.log(targetWidth);
} else {
let scale = targetWidth / 1280; //原图宽高比例
targetWidth = 1280;
targetHeight = targetHeight / scale;
console.log(targetHeight);
}
//缩放后高度仍然大于最大高度继续按比例缩小
canvas.width = targetWidth; //canvas的宽=图片的宽
canvas.height = targetHeight; //canvas的高=图片的高
context.clearRect(0, 0, canvas.width, canvas.height);
context.drawImage(this, 0, 0, canvas.width, canvas.height);
let data = "";
console.log(files);
// 如果图片小于1Mb,不进行压缩,并返回二进制流
if (files.size <= 1048288) {
// 压缩文件大小比例
data = canvas.toDataURL("image/jpeg");
console.log(data);
formData.append("file", files);
// _this.uploadData(formData, files, index);
}
// 如果图片大于1Mb,进行压缩,并返回二进制流
else {
data = canvas.toDataURL("image/jpeg", 0.4);
console.log(data);
let paper = _this.dataURLtoFile(data, files.name);
formData.append("file", paper);
}
let fileArr = [];
fileArr.push(data);
_this.fileList[_this.account].push(...fileArr);
// 清空选中文件,以备下一个文件上传
_this.$refs.selectFile.value = "";
_this.uploadData(formData, files, index);
// _this.source = ideaService.uploadFile();
};
} catch (e) {
console.log("error", e);
// 提示:文件格式不正确,请重新选择!
}
};
},
// 封装实现图片压缩方法
// 将base64转换为file文件
dataURLtoFile(dataurl, filename) {
let arr = dataurl.split(",");
let mime = arr[0].match(/:(.*?);/)[1];
let bstr = atob(arr[1]);
let n = bstr.length;
let u8arr = new Uint8Array(n);
while (n--) {
u8arr[n] = bstr.charCodeAt(n);
}
return new File([u8arr], filename, { type: mime });
},
// 上传文件到后台
uploadData(formData, files, index) {
this.achieve = false;
if (files) {
ideaService.uploadFile(formData).then(res => {
if (res.data.errno === 0) {
this.pathItems.push([]);
this.pathItems[index].push(res.data.data);
this.$toast.success("文件上传成功");
this.achieve = true;
// this.filePath = res.data.data.name;
} else {
this.$toast.fail(res.data.data.message);
}
});
}
},