可能在项目中大家都会遇到文件上传的需求,比如头像,图片等,但是太大的文件上传会给服务器造成很大大压力,那么我们就需要压缩上传的文件
其实这儿所说的压缩,就是图片重绘,改变图片大小
首先我们看一下代码:
<div style="color: #646566;font-size: 0.37333rem;">上传材料图片:<span style="color: #AAAAAA;">(最多上传20张)</span></div>
<van-uploader v-model="fileList" multiple :after-read="afterRead" :before-read="beforeread" preview-size="105px" :max-count="20" @delete="deleteMessage" upload-icon="plus" style="padding-left: 0;margin-top: 10px;" />
data(){
imagePath:[],
fileList: [],
}
methods:{
dataURLtoFile (dataurl, filename) { // 将base64转换为file文件
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)
}
let file = new File([u8arr], filename, {type: mime})
const data = { //拼成你所需要传给后端的格式
file:file,
content:dataurl,
message:'',
status:''
}
return data
},
compress(file){ //压缩的主要代码
let canvas = document.createElement('canvas') // 创建Canvas对象(画布)
let context = canvas.getContext('2d')
let img = new Image()
img.src = file.content // 指定图片的DataURL(图片的base64编码数据)
// console.log(img.src)
img.onload = () =>{ //固定宽高
canvas.width = 400
canvas.height = 300
context.drawImage(img, 0, 0, 400, 300)
file.content = canvas.toDataURL(file.file.type, 0.92) // 0.92为默认压缩质量
let files = this.dataURLtoFile(file.content, file.file.name)
this.imagePath.push(files)
}
//img.onload = () =>{ //按照比例
// let width = 400
// let height = width / (img.naturalWidth / img.naturalHeight)
// canvas.width = width
// canvas.height = height
// context.drawImage(img, 0, 0, canvas.width, canvas.height)
// file.content = canvas.toDataURL(file.file.type, 0.92) // 0.92为默认压缩质量
// let files = this.dataURLtoFile(file.content, file.file.name)
// this.imagePath.push(files)
//}
},
//文件读取完成后执行 图片上传
afterRead(file) {
var that = this
console.log(file)
if (file.length>1) { //只有多选的时候进行压缩
for(var i=0;i<file.length;i++){
if(file[i].file.size > 10000){
that.compress(file[i])
}else{
let files = that.dataURLtoFile(file[i].content, file[i].file.name)
that.imagePath.push(files)
}
}
setTimeout(function(){ //执行顺序 等压缩完了再上传
uploadImages({
fileList:that.imagePath
}).then((res) => {
if (res.code == 200) {
for (let i = 0; i < res.data.length; i++) {
that.files.push(res.data[i])
that.imagePath = []
}
} else {
Toast(res.msg);
}
})
})
}else{
var that = this
let arrs = []
arrs.push(file)
uploadImages({
fileList: arrs
}).then((res) => {
if (res.code == 200) {
for (let i = 0; i < res.data.length; i++) {
that.coverImg.push(res.data[i])
}
} else {
Toast(res.msg);
}
})
}
},
}