input 压缩上传图片vue

mac2025-09-22  35

<!-- --> <template> <div> <img :src="sdimg" @click="bgclick()"> <!-- 图片 --> <input type="file" style="display:none;" accept="image/*" ref="upload" @change="uploadfiles($event)"> </div> </template> <script src="http://libs.baidu.com/jquery/1.9.1/jquery.js"></script> <script> import { Toast,Indicator } from 'mint-ui' import $ from 'jquery' export default { props:['sdimg'], data () { return { } }, components: {}, computed: { }, methods: { bgclick(){ this.$refs.upload.click() } , uploadfile(e){ var that = this; var inputDOM = that.$refs.upload; var file = inputDOM.files; var formData = new FormData(); var filename=file[0].name var n=filename.lastIndexOf('.')+1 var filetype=filename.substring(n) formData.append('file', file[0]); console.log(filetype) if(filetype!=='jpg'&&filetype!=='png'&&filetype!=='ico'&&filetype!=='svg'){ Toast('只允许上传jpg,png,svg,ico格式,请重新上传') return }else if(file[0].size<=0){ Toast('不能上传空的图片') return }else{ Indicator.open({ spinnerType: 'fading-circle' }) $.ajax({ url: this.api.uploadurl, type: "post", data: formData , processData: false, contentType: false, success: function(res) { Indicator.close() console.log(res) if(res.code===200){ Toast('上传成功') let path=that.api.imghead+res.result.relativePath that.$emit('successupload',path,res.result.relativePath) }else{ Toast(res.message) } }, error: function(error){ Toast('上传失败,请稍后再试') } }); } }, uploadfiles(el) { console.log(el.target.files) if (!el.target.files[0].size){ Toast("请选择图片文件") return }else{ this.fileList(el.target); el.target.value = '' } }, //判断是否为文件夹文件 fileList(fileList) { let files = fileList.files[0]; // console.log(typeof fileList) //判断是否为文件夹 console.log(files.type) if (files.type != '') { this.fileAdd(files); } else { this.$msgbox("请选择图片文件") } }, fileAdd(file) { //判断是否为图片文件 if (file.type.indexOf('image') == -1) { Toast("请选择图片文件") } else { let reader = new FileReader(); let image = new Image(); let _this = this; reader.readAsDataURL(file); reader.onload = function () { file.src = this.result; image.onload = function(){ let width = image.width; let height = image.height; file.width = width; file.height = height; _this.imgL = file.src //页面上显示所选择的图片 }; // console.log(file) console.log(file.size/1024) if(file.size/1024 > 1025){ //判断图片的大小,超过1M 进行压缩 _this.imgCompress(file,{quality: 0.2}) }else{ _this.partitionBase = file.src.split(",")[1] //这里是因为后台需要 base64和图片type类型两个数据,所以进行了处理 _this.imgType =file.type.split("/")[1] Indicator.open({ spinnerType: 'fading-circle' }) _this.axios.post('/questionnaire/file/uploadByBase64',{ base64Str:_this.partitionBase, fileType:_this.imgType }).then(res=>{ Indicator.close() if(res.data.code===200){ Toast('上传成功') let path=_this.api.imghead+res.data.result.relativePath _this.$emit('successupload',path,res.data.result.relativePath) }else{ Toast((res.data.message)) } }).catch(err=>{ Indicator.close() Toast('上传失败,请稍后再试') }) } } } }, //图片压缩 imgCompress(path,obj){ //path是指上传的图片,obj是压缩的品质,越低越模糊 let _this = this //这里的this 是把vue的实例对象指向改变为_this var img = new Image(); img.src = path.src; img.onload = function(){ var that = this; //这里的this 是把img的对象指向改变为that // 默认按比例压缩 var w = that.width, h = that.height, scale = w / h; w = obj.width || w; h = obj.height || (w / scale); var quality = 0.7; // 默认图片质量为0.7 //生成canvas var canvas = document.createElement('canvas'); var ctx = canvas.getContext('2d'); // 创建属性节点 var anw = document.createAttribute("width"); anw.nodeValue = w; var anh = document.createAttribute("height"); anh.nodeValue = h; canvas.setAttributeNode(anw); canvas.setAttributeNode(anh); ctx.drawImage(that, 0, 0, w, h); // 图像质量 if(obj.quality && obj.quality <= 1 && obj.quality > 0){ quality = obj.quality; } // quality值越小,所绘制出的图像越模糊 var base64 = canvas.toDataURL('image/jpeg', quality); // 回调函数返回base64的值 var urlFile = _this.convertBase64UrlToBlob(base64) //这个地方的处理是为了把压缩的base64转化为对象,获得压缩后图片的大小size,方便对压缩后的图片再次进行判断; console.log(urlFile.size/1024) if(urlFile.size/1024 > 1025){ Toast("图片过大,请重新上传图片") }else{ _this.partitionBase = base64.split(",")[1] _this.imgType =urlFile.type.split("/")[1] console.log(urlFile.type) Indicator.open({ spinnerType: 'fading-circle' }) _this.axios.post('/questionnaire/file/uploadByBase64',{ base64Str:_this.partitionBase, fileType:_this.imgType }).then(res=>{ Indicator.close() if(res.data.code===200){ let path=_this.api.imghead+res.data.result.relativePath _this.$emit('successupload',path,res.data.result.relativePath) Toast('上传成功') }else{ Toast(res.data.message) } }).catch(err=>{ Indicator.close() Toast('上传失败,请稍后再试') }) // $.ajax({ // url: _this.api.uploadImgurl, // type: "post", // data: {'base64Str':_this.partitionBase,'fileType':_this.imgType}, // processData: false, // contentType: false, // success: function(res) { // Indicator.close() // console.log(res) // if(res.code===200){ // Toast('上传成功') // let path=_this.api.imghead+res.result.relativePath // _this.$emit('successupload',path,res.result.relativePath) // }else{ // Toast(res.message) // } // }, // error: function(error){ // Indicator.close() // Toast('上传失败,请稍后再试') // } // }); } } }, //将base64码转化为file(Blob) //此处函数对压缩后的base64经过处理返回{size: "", type: ""} convertBase64UrlToBlob(urlData){ var arr = urlData.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}); }, }, mounted(){ } } </script> <style lang='scss' scoped> img{ width:100%; height:100%; } </style>
最新回复(0)