【vue+el-upload+vue-cropper】vue图片上传,vue-cropper图片裁剪后上传

在这里插入图片描述

一. 先看效果演示

在这里插入图片描述

二. 图片上传

用的el-upload加el-image组件
html部分

<el-dialog>
...//无关代码已省略
	<div v-for="item in imgArr" :key="item.index">
      <span>{{ item.name }}</span>
      <el-upload action="#" list-type="picture-card" :on-change="onChange.bind(null, item.index)" :auto-upload="false" :file-list="item.fileList" :class="{ hide: item.hideUpload }">
          <i slot="default" class="el-icon-plus"></i>
          <div slot="file" slot-scope="{ file }">
            <el-image class="el-upload-list__item-thumbnail" :src="item.aimgSrc" alt="" :onerror="defaultImg" :preview-src-list="item.fileList"></el-image>
            <span class="el-upload-list__item-actions">
            	// 预览按钮
              <span class="el-upload-list__item-preview" @click="handlePictureCardPreview(file)">
                <i class="el-icon-zoom-in"></i>
              </span>
              	// 删除按钮
              <span class="el-upload-list__item-delete" @click="handleRemove(file, item.index)">
                <i class="el-icon-delete"></i>
              </span>
              	// 裁剪按钮
              <span v-if="item.index == 6" class="el-upload-list__item-delete" @click="beforeCrop(file)">
                <i class="el-icon-scissors"></i>
              </span>
            </span>
          </div>
        </el-upload>
	</div>
</el-dialog>
....

注释:
el-upload
:on-change=“onChange.bind(null, item.index)” 不加.bind会报错,
:auto-upload=“false” 表示不自动上传,也就是手动上传
:file-list=“item.fileList” 上传的图片列表,数组对象格式[{url:xxxx}]
:class=“{ hide: item.hideUpload }” 到el-image使用,上传完后影藏那个加号和虚线框

el-image
:οnerrοr=“defaultImg” 图片加载失败,报错时候的默认图片.
:preview-src-list=“item.fileList” 预览的图片列表,同:file-list=“item.fileList”

预览,删除,裁剪,三个按钮,目前功能与预览无关,预览功能有空再另写吧

js部分


      imgArr: [
        // aimgFile调接口, aimgSrc回显, hideUpload影藏加号, fileList预览大图
        { index: 0, name: '图片A:', aimgFile: '', aimgSrc: '', hideUpload: false, fileList: [] },
        { index: 1, name: '图片A:', aimgFile: '', aimgSrc: '', hideUpload: false, fileList: [] },
        { index: 2, name: '图片A:', aimgFile: '', aimgSrc: '', hideUpload: false, fileList: [] },
        { index: 3, name: '图片A:', aimgFile: '', aimgSrc: '', hideUpload: false, fileList: [] },
        { index: 4, name: '图片A:', aimgFile: '', aimgSrc: '', hideUpload: false, fileList: [] },
        { index: 5, name: '图片A:', aimgFile: '', aimgSrc: '', hideUpload: false, fileList: [] },
        { index: 6, name: '图片A:', aimgFile: '', aimgSrc: '', hideUpload: false, fileList: [] },
      ],
      files :'', //裁剪图片的标记
      
    // 上传图片 index 图片下标 file图片内容 flag裁剪图片的标记
    onChange(index, file, flag) {
      this.files = file.raw
      const isJPG = file.raw.type === 'image/jpeg' || file.raw.type == 'image/png'
      const isLt2M = file.raw.size / 1024 / 1024 < 2
      if (!isJPG) {
        this.$message.error('上传图片只能是 JPG 或 PNG 格式!')
        this.handleRemove(file.raw, index)
        return
      }
      if (!isLt2M) {
        this.$message.error('上传图片大小不能超过 2MB!')
        this.handleRemove(file.raw, index)
        return
      }
      // 上传图片
      const fileData = new FormData()
      fileData.append('imgFile', file.raw)
      fileData.append('imgType', 1)
      // 调接口
      doctorAccessoryUpload(fileData).then((res) => {
        if (res) {
          this.imgArr[index].hideUpload = true
          this.imgArr[index].aimgSrc = file.url
          this.imgArr[index].aimgFile = res.result
          // 裁剪后上传
          if (flag === 1) this.imgArr[index].fileList = [{ url: file.url }]
        } else {
          this.handleRemove(file.raw, index)
        }
      })
    },
    // 删除上传图片
    handleRemove(file, index) {
      this.imgArr[index].aimgSrc = ''
      this.imgArr[index].aimgFile = ''
      this.imgArr[index].fileList = []
      this.imgArr[index].hideUpload = false
    },
三. 裁剪图片

下载vueCropper插件

	npm i vue-cropper --save  // 我的版本是^0.6.4

另起一个dialog

      <!-- 图片裁剪 -->
      <el-dialog title="图片裁剪" :visible.sync="cropDialog" width="40%" :modal="true" :close-on-click-modal="false" center @close="cropCancles" v-dialogDrag>
        <div class="cropBox">
          <template>
            <div>
              <vueCropper
                @mouseenter.native="enter"
                @mouseleave.native="leave"
                ref="cropper"
                :img="option.uploadImg"
                :outputSize="option.size"
                :outputType="option.outputType"
                :info="true"
                :full="option.full"
                :canMove="option.canMove"
                :canMoveBox="option.canMoveBox"
                :original="option.original"
                :autoCrop="option.autoCrop"
                :fixed="option.fixed"
                :fixedNumber="option.fixedNumber"
                :centerBox="option.centerBox"
                :infoTrue="option.infoTrue"
                :fixedBox="option.fixedBox"
              ></vueCropper>
            </div>
          </template>
          <div>
            <img :src="cropImg" alt="" />
          </div>
        </div>
        <div slot="footer">
          <el-button @click="cropCancles">取 消</el-button>
          <el-button type="primary" @click="cropConfirm">裁剪图片</el-button>
        </div>
      </el-dialog>
      <script>
      import { VueCropper } from 'vue-cropper'
      export default {
  		components: { VueCropper },
  		data() {
		    return {
	          cropDialog: false,
		      option: {
		        uploadImg: '', // 原图地址
		        info: true, // 裁剪框的大小信息
		        outputSize: 1, // 裁剪生成图片的质量
		        outputType: 'jpeg', // 裁剪生成图片的格式
		        canScale: true, // 图片是否允许滚轮缩放
		        autoCrop: true, // 是否默认生成截图框
		        fixedBox: true, // 固定截图框大小 不允许改变
		        fixed: true, // 是否开启截图框宽高固定比例
		        fixedNumber: [3, 4], // 截图框的宽高比例
		        full: false, // 是否输出原图比例的截图
		        canMove: true, //是否可以移动原图
		        canMoveBox: true, // 截图框能否拖动
		        original: false, // 上传图片按照原始比例渲染
		        centerBox: true, // 截图框是否被限制在图片里面
		        infoTrue: false, // true 为展示真实输出图片宽高 false 展示看到的截图框宽高
		      },
		      cropImg: require('../../public/img/default.png'),
			}
		}
		  //开始裁剪
	    enter() {
	      if (this.option.uploadImg == '') {
	        return
	      }
	      this.$refs.cropper.startCrop()
	    },
	    //停止裁剪
	    leave() {
	      this.$refs.cropper.stopCrop()
	      this.$refs.cropper.getCropData((data) => {
	        this.cropImg = data
	      })
	    },
	    // 裁剪前
	    beforeCrop(file) {
	      this.option.uploadImg = file.url
	      this.cropDialog = true
	      setTimeout(() => {
	        this.$refs.cropper.getCropData((data) => {
	          this.cropImg = data
	        })
	      }, 500)
	    },
	    // 确认裁剪
	    cropConfirm() {
	      //获取截图的base64格式数据
	      this.$refs.cropper.getCropData((data) => {
	        this.cropImg = data
	        this.handleRemove(this.files, this.imgArr.length - 1)
	        this.cropCancles()
	        setTimeout(() => {
	          this.onChange(this.imgArr.length - 1, { raw: this.dataURLtoFile(data, 'Default.jpg'), url: data }, 1)
	        }, 1000)
	      })
	    },
	    // 取消裁剪
	    cropCancles() {
	      this.cropDialog = false
	      this.option.uploadImg = ''
	      this.cropImg = require('../../public/img/default.png')
	    },
	    // base64转file
	    dataURLtoFile(dataurl, filename) {
	      let arr = dataurl.split(',')
	      let mime = arr[0].match(/:(.*?);/)[1]
	      let bstr = atob(arr[1])
	      let n = bstr.length
	      let u8arr = new Uint8Array(n)
	      while (n--) {
	        u8arr[n] = bstr.charCodeAt(n)
	      }
	      return new File([u8arr], filename, { type: mime })
	    },
	  }
      </script>

ok 结束了,记录一下

  • 7
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 4
    评论
要使用vant-uploader和vue-cropper来实现裁剪图片并上,你可以按照以下步骤进行操作: 1. 首先,安装vant和vue-cropper插件。你可以使用npm或yarn来安装它们。 2. 在你的Vue组件中,引入vant-uploader和vue-cropper组件。 3. 在模板中,使用vant-uploader组件来实现图片功能。设置上的action属性为你的上接口地址,并设置on-success事件来处理上成功后的逻辑。 4. 在on-success事件中,获取到上成功后的图片地址,并将其递给vue-cropper组件。 5. 在vue-cropper组件中,设置裁剪框的样式和裁剪比例等属性。使用v-model指令来绑定裁剪后的图片数据。 6. 在提交按钮的点击事件中,将裁剪后的图片数据上到服务器。 下面是一个简单的示例代码: ```vue <template> <div> <van-uploader action="/upload" :on-success="handleUploadSuccess" ></van-uploader> <vue-cropper v-if="showCropper" :src="cropperSrc" :output-size="{ width: 200, height: 200 }" :output-type="'jpeg'" :fixed-box="true" :fixed-number="\[1, 1\]" v-model="croppedImage" ></vue-cropper> <button @click="handleSubmit">提交</button> </div> </template> <script> import { VanUploader } from 'vant'; import VueCropper from 'vue-cropper'; export default { components: { VanUploader, VueCropper, }, data() { return { showCropper: false, cropperSrc: '', croppedImage: '', }; }, methods: { handleUploadSuccess(response) { // 获取上成功后的图片地址 const imageUrl = response.data.imageUrl; // 显示裁剪组件 this.showCropper = true; // 设置裁剪组件的图片地址 this.cropperSrc = imageUrl; }, handleSubmit() { // 提交裁剪后的图片数据到服务器 // this.croppedImage 包含裁剪后的图片数据 }, }, }; </script> ``` 请注意,以上代码只是一个简单的示例,你需要根据你的实际需求进行适当的修改和调整。同时,你还需要在后端实现相应的上裁剪功能。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

杨同学*

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值