input 压缩上传图片 vue

<!--  -->
<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
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值