el-upload与vue-cropperjs在vue3项目中的应用-实现图片裁剪后再上传服务器

      实现图片剪裁后再上传服务器,用到了两个开源组件,需要在项目中引入 element-plus 中的 el-upload 和 vue-cropperjs,直接上代码。 

<template>
  <div>
      <el-upload ref="elUpload"
        action="/sys-file/upload"
        accept=".jpg,.png"
        :headers="headers"
        :auto-upload="false"
        :on-change="uploadChange"
        :http-request='httpRequest'>
          <el-button type="primary">点击上传</el-button>
      </el-upload>
      <img :src="url" />
      <el-dialog title="图片裁剪" v-model="showCopper" append-to-body>
        <vue-cropper
          ref="cropper"
          :src="imgSrc"
          preview=".preview"/>
        <template #footer>
          <el-button type="primary" @click="confirmFn">确 定</el-button>
        </template>
      </el-dialog>
  </div>
</template>
<script>
  import store from '@/store'
  import VueCropper from 'vue-cropperjs';
  import request from '@/utils/axios'
  import 'cropperjs/dist/cropper.css';
  import { ref } from 'vue'
  export default {
    components: {
      VueCropper
    },
    setup() {
      const cropper = ref(null);
      const elUpload = ref(null);
      const imgSrc = ref('');
      const url = ref('');
      const showCopper = ref(false);
      const headers = {
          Authorization: 'Bearer ' + store.getters.access_token
      }
      const uploadChange = (file) => {
        const url = file.raw;
        const reader = new FileReader();
        reader.onload = (event) => {
          imgSrc.value = event.target.result;
          cropper.value.replace(event.target.result);
        };
        reader.readAsDataURL(url);
        showCopper.value = true;
      }
      const uploadFile = ref('');
      const httpRequest = (requestdata) => {
        let { action, headers, filename } = requestdata;
        action = action.substring(5)
        const formData = new FormData();
        formData.append(filename, uploadFile.value)
        request({
          headers: headers,
          url: action,
          method: 'post',
          data: formData
        }).then(res => {
          //调用上传接口后的处理
          url.value = res.data.url;
        })
      }
      const confirmFn = () => {
        cropper.value.getCroppedCanvas().toBlob((blob) => {
          uploadFile.value = blob
          elUpload.value.submit()
          showCopper.value = false;
        })
      }
      return {
        headers,
        cropper,
        elUpload,
        imgSrc,
        url,
        showCopper,
        uploadChange,
        httpRequest,
        confirmFn
      }
    }
  }
</script>
评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值