vue-element-admin vue-cropper 图片裁切组件并上传到阿里云OSS

1、安装

npm install vue-cropper

2、完整代码

<template>
  <div v-loading="Loading" class="app-container accountIndex">

    <el-image class="round" style="width: 160px; height: 160px" :src="logo" fit="cover">
    </el-image>

    <el-upload ref="pic" class="upload-logo" list-type="picture-card" action="" :auto-upload="false"
      :on-change="beforeCropperUpload" :show-file-list="false">
      上传图片
    </el-upload>

    <!-- vueCropper 剪裁图片实现-->
    <el-dialog title="图片剪裁" :visible.sync="dialogCropper.show" append-to-body>
      <div class="cropper-content">
        <div class="cropper" style="text-align:center">
          <vueCropper ref="cropper" :img="dialogCropper.option.img" :outputSize="dialogCropper.option.size"
            :outputType="dialogCropper.option.outputType" :info="true" :full="dialogCropper.option.full"
            :canMove="dialogCropper.option.canMove" :canMoveBox="dialogCropper.option.canMoveBox"
            :original="dialogCropper.option.original" :autoCrop="dialogCropper.option.autoCrop"
            :fixed="dialogCropper.option.fixed" :fixedNumber="dialogCropper.option.fixedNumber"
            :centerBox="dialogCropper.option.centerBox" :infoTrue="dialogCropper.option.infoTrue"
            :fixedBox="dialogCropper.option.fixedBox"></vueCropper>
        </div>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogCropper.show = false">取 消</el-button>
        <el-button type="success" @click="primaryCropper">确 认</el-button>
      </div>
    </el-dialog>
    <!-- vueCropper 剪裁图片实现-->

  </div>
</template>

<script>
  import {
    VueCropper
  } from 'vue-cropper'
  import OSS from 'ali-oss'
  import {
    aliOSSToken,
  } from '@/api/goods'
  export default {
    name: 'accountIndex',
    components: {
      VueCropper,
    },
    data() {
      return {
        Loading: false,
        logo:'',
        ossData: {},
        //裁剪图片窗口
        dialogCropper: {
          show: false,
          option: {
            img: '', // 裁剪图片的地址
            info: true, // 裁剪框的大小信息
            outputSize: 0.8, // 裁剪生成图片的质量
            outputType: 'png', // 裁剪生成图片的格式
            canScale: false, // 图片是否允许滚轮缩放
            autoCrop: true, // 是否默认生成截图框
            autoCropWidth: 200, // 默认生成截图框宽度
            autoCropHeight: 200, // 默认生成截图框高度
            fixedBox: true, // 固定截图框大小 不允许改变
            fixed: true, // 是否开启截图框宽高固定比例
            fixedNumber: [1, 1], // 截图框的宽高比例
            full: true, // 是否输出原图比例的截图
            canMove: true, //能否拖动图片
            canMoveBox: false, // 截图框能否拖动
            original: false, // 上传图片按照原始比例渲染
            centerBox: false, // 截图框是否被限制在图片里面
            infoTrue: true, // true 为展示真实输出图片宽高 false 展示看到的截图框宽高
          },
        },
      }
    },
    created() {
      this.getAliOSSToken();
    },
    methods: {
      /**
       * 获取OSS配置信息
       */
      getAliOSSToken() {
        this.Loading = true
        aliOSSToken().then(response => {
          // console.log('==response==', JSON.stringify(response))
          this.ossData = response
          this.Loading = false
        }).catch((e) => {
          this.Loading = false
          this.$message.error('' + e)
          console.log('error submit!!', e)
        })
      },
      /**
       * 上传按钮   限制图片大小
       * @param {Object} file
       * @param {Object} fileList
       */
      beforeCropperUpload(file, fileList) {
        const isJPG = file.name.substring(file.name.lastIndexOf('.') + 1) === 'jpeg' || file.name.substring(file.name
          .lastIndexOf('.') + 1) === 'jpg'
        const isPNG = file.name.substring(file.name.lastIndexOf('.') + 1) === 'png'
        const isLt2M = file.size / 1024 / 1024 < 2
        if (!isJPG && !isPNG) {
          this.$message.error('上传图片只能是 JPG、PNG 格式!')
          return false
        }
        if (!isLt2M) {
          this.$message.error('上传图片大小不能超过 2MB!')
          return false
        }
        var reader = new FileReader();
        let data
        reader.onload = (e) => {
          let data;
          if (typeof e.target.result === 'object') {
            // 把Array Buffer转化为blob 如果是base64不需要
            data = window.URL.createObjectURL(new Blob([e.target.result]))
          } else {
            data = e.target.result
          }
        }
        this.$nextTick(() => {
          this.dialogCropper.option.img = file.url
          this.dialogCropper.show = true
        })
      },
      /**
       * 点击裁剪,这一步是可以拿到处理后的地址
       */
      primaryCropper() {
        this.$refs.cropper.getCropBlob((file) => {
          //上传到OSS上
          const clientOSS = new OSS({
            cname: true, // 开启自定义域名上传
            endpoint: 'http://xxx.aliyuncs.com/', // 自己的域名
            region: 'oss-cn-xxx',
            accessKeyId: this.ossData.AccessKeyId, // 查看你自己的阿里云KEY
            accessKeySecret: this.ossData.AccessKeySecret, // 查看自己的阿里云KEYSECRET
            stsToken: this.ossData.SecurityToken,
            bucket: 'xxx' // 你的 OSS bucket 名称
          })
          // console.log("clientOSS", clientOSS)
          try {
            const date = new Date().getTime()
            const fileNames = 'xxx/' + `/${date}` + '.png'
            // 上传文件,这里是上传到OSS的 uploads文件夹下
            this.Loading = true
            clientOSS.put(fileNames, file).then(res => {
              if (res.res.statusCode === 200) {
                console.log("clientOSS", res)
                this.logo = res.url;
                this.dialogCropper.show = false;
              }
              this.Loading = false
            })
          } catch (e) {
            this.Loading = false
            console.log(e)
          }
        })
      },
    }
  }
</script>
<style>
  /* 截图 */
  .cropper {
    width: auto;
    height: 300px;
  }
</style>

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值