el-upload 上传文件配合VueCropper裁切尺寸上传七牛云

2 篇文章 0 订阅
1 篇文章 0 订阅

因为之前有很详细说过el-upload上传七牛云 所以这次简单粗暴些
1.直接贴代码

<template>
  <div>
    <img  :src="options.img" @click="editCropper()" title="点击上传logo" class="img-circle img-lg" />
    <el-dialog :title="title" :visible.sync="open" width="1300px">
      <el-row>
        <el-col :xs="24" :md="12" :style="{height: '350px'}">
          <vue-cropper
            ref="cropper"
            :img="options.img"
            :info="true"
            :autoCrop="options.autoCrop"
            :autoCropWidth="options.autoCropWidth"
            :autoCropHeight="options.autoCropHeight"
            :fixedBox="options.fixedBox"
            
            @realTime="realTime"
          />
        </el-col>
        <el-col :xs="24" :md="12" :style="{height: '350px'}">
          <el-row class="avatar-upload-preview">
            <img :src="previews.url" :style="previews.img" />
          </el-row>
        </el-col>
      </el-row>
      <br />
      <el-row>
        <el-upload
          :show-file-list="false"
          :before-upload="beforeUpload"
          :action="qn"
          :data="postData"
          :on-success="handleAvatarSuccess"
         
        >
          <el-button size="small">
            上传图片
          </el-button>
        </el-upload>

        <el-button icon="el-icon-plus" size="small" @click="changeScale(1)"></el-button>

        <el-button icon="el-icon-minus" size="small" @click="changeScale(-1)"></el-button>

        <el-button icon="el-icon-refresh-left" size="small" @click="rotateLeft()"></el-button>

        <el-button icon="el-icon-refresh-right" size="small" @click="rotateRight()"></el-button>

        <el-button type="primary" size="small" @click="finish()">保存</el-button>
      </el-row>
    </el-dialog>
  </div>
</template>

<script>
import store from "@/store";
import { VueCropper } from "vue-cropper";
import { uploadAvatar } from "@/api/system/user";
 import {upadaQiNu} from '@/api/index'
import * as qiniu from "qiniu-js";
 
export default {
  components: { VueCropper },
  props: {
    fileUrl: {
      type: String
    },
    index:Number
  },
  data() {
    return {
      // 是否显示弹出层
      action: null,
      open: false,
      // 弹出层标题
      title: "裁切Logo",
      postData: {
        token: ''
      },
      BASE_URL:"",
      qn: null,
      options: {
        img: '', //裁剪图片的地址
        autoCrop: true, // 是否默认生成截图框
        autoCropWidth: 200, // 默认生成截图框宽度
        autoCropHeight: 200, // 默认生成截图框高度
        fixedBox: true // 固定截图框大小 不允许改变
      },
      myHashUrl:'',
      previews: {}
    };
  },
  created() {
      this.getqiNiu()
  },
   watch: {
    fileUrl: {
      handler(newValue, oldValue) {
           
           
        //父组件param对象改变会触发此函数
        this.options.img=this.BASE_URL+newValue 
  
      },
      deep: true
    }
  },
  methods: {
      finish() {
      this.$refs.cropper.getCropBlob((data) => {
          const reader = new FileReader();
        reader.readAsDataURL(data);
        reader.onload = (e) => {
          
          let size = e.total
           
           
          // this.options.img = reader.result;
           
           
        
        this.putb64(reader.result)
        };
     
      
      })
    },
     putb64(picBase) {
       let than = this
      /*picUrl用来存储返回来的url*/
       
      /*把头部的data:image/png;base64,去掉。(注意:base64后面的逗号也去掉)*/
      picBase = picBase.substring(23);
      /*通过base64编码字符流计算文件流大小函数*/
      
      let url = "http://upload-z2.qiniup.com/putb64/" +this.fileSize(picBase);
      let xhr = new XMLHttpRequest();
      xhr.onreadystatechange = function() {
            if (xhr.readyState == 4) {
                  let keyText =JSON.parse(xhr.responseText) ;
                   
                    than.uploadImg(keyText.hash)
            }
      }
      xhr.open("POST", url, false);
      xhr.setRequestHeader("Content-Type", "application/octet-stream");
      xhr.setRequestHeader("Authorization","UpToken "+this.postData.token);
      xhr.send(picBase);
},
 fileSize(str) {
            let fileSize;
            if (str.indexOf('=') > 0) {
                  let indexOf = str.indexOf('=');
                  str = str.substring(0, indexOf); //把末尾的’=‘号去掉
            }
            fileSize = parseInt(str.length - (str.length / 8) * 2);
            return fileSize;
      },
      /*把字符串转换成json*/
       strToJson(str) {
            let json = eval('(' + str + ')');
            return json;
      },
     getqiNiu() {
      const config = {
        useCdnDomain: true,
        region: qiniu.region.z2
      };
      const getUrl = qiniu.getUploadUrl(config);
      getUrl.then(res => {
        this.qn = res;
      });
    
      this.postData.token=this.$store.state.user.setUpdataToken.token
      this.BASE_URL=this.$store.state.user.setUpdataToken.url
      this.options.img =this.BASE_URL+ this.fileUrl 
      this.myHashUrl=this.fileUrl
    },
    // 编辑头像
    editCropper() {
      this.open = true;
    },
    // 向左旋转
    rotateLeft() {
      this.$refs.cropper.rotateLeft();
    },
    // 向右旋转
    rotateRight() {
      this.$refs.cropper.rotateRight();
    },
    // 图片缩放
    changeScale(num) {
      num = num || 1;
      this.$refs.cropper.changeScale(num);
    },
    // 上传预处理
    beforeUpload(file) {
       
      if (file.type.indexOf("image/") == -1) {
        this.msgError("文件格式错误,请上传图片类型,如:JPG,PNG后缀的文件。");
      } else {
        const reader = new FileReader();
        reader.readAsDataURL(file);
        reader.onload = () => {
          // this.options.img = reader.result;
           
           
        };
      }
    },
   
    // 上传图片
    uploadImg(myHashUrl) {
        this.$emit('setUpData',{
              index:this.index,
              hash:myHashUrl
            })
            this.open=false
    },
    handleAvatarSuccess(response, file) {
            this.options.img = this.BASE_URL + response.hash;
            this.myHashUrl = response.hash
             
        this.msgSuccess("修改成功");
       
      // this.$refs.cropper.clearCrop();
    },

    // 实时预览
    realTime(data) {
 
        this.previews=data
    }
  }
};
</script>

注意事项
1.裁切完成之后将图片信息转下base64 然后看到我代码注释处理下
2.七牛云上传base64位图片空间地址要加/putb64后面再加/处理过的base64文件字符串
3.裁剪完成的图片再次发生ajax时建议使用原生new XMLHttpRequest()发送
4.最后祝男的漂亮 女的帅气 本人是个开荒者 代码风格和规范有不足之处还请多多批评

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值