vue中,使用input实现文件预览和压缩上传

html代码:

<div>
<img :src="showImg" alt="" style="height: 300px;">
<span class="aaaa" @click="uploadFile">通知书上传<input id="upload" type="file" style="display: none;" v-on:change="readLocalFile()"></span>
</div>

 

js代码:

uploadFile(){
    document.getElementById("upload").click();            
},
readLocalFile(){
    let _this = this;
    let localFile = document.getElementById("upload").files[0];
    if (!localFile) return;
    //获取图片的大小,M为单位
    let limitSize = localFile.size / 1024 / 1024;
    let reader = new FileReader();
    reader.readAsDataURL(localFile, "UTF-8")
    reader.onload = function(e){                
        //本地图片预览
        _this.showImg = e.target.result;                    
        //图片如果大于4M,那么需要进行图片的压缩
        if(limitSize >= 4){
            //使用canvas压缩图片
            let width = 400; //图像大小
            let quality = 0.6; //图像质量
            let base64 = '';
            let canvas = document.createElement("canvas");
            let drawer = canvas.getContext("2d");
            let img = new Image();//实例化一个图片
            img.src = e.target.result;//给图片src赋值
            img.onload = function(){
                //给canvas设置宽高
                canvas.width = width;
                canvas.height = width * (img.height / img.width);
                drawer.drawImage(img, 0, 0, canvas.width, canvas.height);
                //把图片转换成base64(这里的base64是上传到后端的格式)
                base64 = canvas.toDataURL("image/png", quality);    
                                
                //上传到后端的逻辑代码
                //......
            }
        }                
    }
    reader.onerror = function(err){
        console.log(err)
    }
}

 

posted @ 2022-08-26 11:09  秃头的铲屎官  Views(355)  Comments(0Edit  收藏  举报