上传图片和压缩
前端处理用户图片, 控制上传图片的大小, 减轻服务器流量压力
- 首先通过input获取图片
<input type="file" accept="image/*" alt="图片" multiple @change="changeImage">
- 获取所有图片数据并添加到一个数组中
let file = e.target.files
let arr = []
for (let i = 0; i < file.length; i ++) {
arr.push(file[i])
}
- 通过遍历判断图片原始文件的大小(这里大小是字节), 来选择是否压缩
- 图片压缩功能实现有很多方法, 我在这里用的是lrz的压缩插件
lrz( value , options).then(function(rst){...})
其中 value : 图片file数据
options : 是lrz插件的设置, 可以再里面设置 quality (压缩比例)
rst : 是插件返回的一个对象, 其中包括 压缩后的 base64格式
因为后台不接收base64格式的图片文件,所以下面进行了格式转换
var blob = this.dataURLtoBlob(rst.base64)
var newfile = this.blobToFile(blob, name)
// newfile 就是最后转换好的格式了
- 下面是完整的代码, 希望能给大家提供帮助
// 上传图片处理
changeImage (e) {
let file = e.target.files
let arr = []
for (let i = 0; i < file.length; i ++) {
arr.push(file[i])
}
// console.log(file)
var options = {
quality: 0.1
}
arr.forEach(function(value,j){
// this.imgList[i].img = window.URL.createObjectURL(file[i])
if (file.size > 1000000) {
lrz( value , options).then(function(rst) {
//成功时执行
var blob = this.dataURLtoBlob(rst.base64)
var newfile = this.blobToFile(blob, name)
this.imgList.push ({
img: newfile,
img64: rst.base64,
index: this.imgLength
} )
this.imgLength ++
}.bind(this)).catch(function(error) {
//失败时执行
console.log('失败', error)
}).always(function() {
//不管成功或失败,都会执行
})
} else {
console.log(1)
this.imgList.push ({
img: value,
img64: URL.createObjectURL(value),
index: this.imgLength
} )
this.imgLength ++
}
}.bind(this))
},
//将base64转换为blob
dataURLtoBlob(dataurl) {
var arr = dataurl.split(","),
mime = arr[0].match(/:(.*?);/)[1],
bstr = atob(arr[1]),
n = bstr.length,
u8arr = new Uint8Array(n);
while (n--) {
u8arr[n] = bstr.charCodeAt(n);
}
return new Blob([u8arr], { type: mime });
},
//将blob转换为file
blobToFile(theBlob, fileName) {
theBlob.lastModifiedDate = new Date()
theBlob.name = fileName;
return theBlob;
},
},