zoukankan      html  css  js  c++  java
  • el-upload配合vue-cropper实现上传图片前裁剪

    需求背景

    上传一个封面图,在上传之前需要对图片进行裁剪,上传裁剪之后的图片,类似微信的上传头像。

    技术方案

    上传肯定是用element的 el-upload 组件实现上传,非常方便,各种钩子函数。

    裁剪一开始找的 cropper 看着功能到是非常齐全,api也比较丰富,基本是符合预期的需求的。但是此库是基于jq 的,在vue项目中有点难用。于是就找到了 vue-cropper 支持组件化的方式,只需要传入相应的配置参数就可以使用,还有一个非常方便的地方是 官网 提供了在线调试页面,更改配置就可以看到效果,配置好之后再把代码复制到项目中,也是相当的方便。

    封装组件

    上传文件的组件:uploadImg.vue

    <template>
      <div :class="$options.name">
        <el-upload
          v-show="!resultImg"
          class="upload-el"
          accept="image/*"
          ref="fileUpload"
          name="pic"
          :action="action"
          :data="uploadData"
          :on-change="selectChange"
          :show-file-list="false"
          :auto-upload="false"
          :http-request="httpRequest">
          <div>
            <span
              class="icon upload-icon" />
            <el-button>选择图片</el-button>
          </div>
          <div
            slot="tip"
            class="el-upload__tip">
            图片大小不超过5M,推荐图片尺寸宽高比9:16
          </div>
        </el-upload>
        <figure
          v-show="resultImg"
          class="result-img">
          <img
            :src="resultImg">
          <el-button
            @click="updateCropper">重新上传</el-button>
        </figure>
        <cropper
          v-if="showCropper"
          :dialog-visible="showCropper"
          :cropper-img="cropperImg"
          @update-cropper="updateCropper"
          @colse-dialog="closeDialog"
          @upload-img="uploadImg" />
      </div>
    </template>
    
    <script>
    import Cropper from './cropper.vue';
    import { baseAxios } from '@common/axios';
    import { loading } from '@common';
    export default {
      name: 'UploadImg',
      components: {
        Cropper
      },
      data () {
        return {
          uploadData: { // 上传需要的额外参数
            siteId: 1,
            source: 1
          },
          action: '/mvod-aliyun/material/uplod/pic', // 上传地址,必填
          cropperImg: '', // 需要裁剪的图片
          showCropper: false, // 是否显示裁剪框
          uploadFile: '', // 裁剪后的文件
          resultImg: '' // 上传成功,后台返回的路径
        };
      },
      methods: {
        // submit 之后会触发此方法
        httpRequest (request) {
          const { action, data, filename } = request;
          // 新建formDate对象
          let formData = new FormData();
          for (let key in data) {
            formData.append(key, data[key]);
          }
          // 文件单独push,第三个参数指定上传的文件名
          formData.append(filename, this.uploadFile, data.fileName);
          loading.start(); // 上传中的loading
          baseAxios({
            headers: {
              contentType: 'multipart/form-data' // 需要指定上传的方式
            },
            url: action,
            method: 'post',
            data: formData,
            timeout: 200000000 // 防止文件过大超时
          }).then(({ data: resp }) => {
            loading.close();
            const { code, data, msg } = resp || {};
            if (code === 0) {
              this.$message.success('图片上传成功');
              this.resultImg = data; // 上传成功后展示的图片
            } else {
              this.$message.error(msg || '网络错误');
            }
          }).catch(err => {
            loading.close();
            console.log(err);
          });
        },
        // 选择文件
        selectChange (file) {
          const { raw } = file;
          this.openCropper(raw);
        },
        /**
         * @param {file} 上传的文件
          */
        openCropper (file) {
          var files = file;
          let isLt5M = files.size > (5 << 20);
          if (isLt5M) {
            this.$message.error('请上传5M内的图片');
            return false;
          }
          var reader = new FileReader();
          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.cropperImg = data;
          };
          // 转化为base64
          // reader.readAsDataURL(file)
          // 转化为blob
          reader.readAsArrayBuffer(files);
          this.showCropper = true;
        },
        // 上传图片
        uploadImg (file) {
          this.uploadFile = file;
          this.$refs.fileUpload.submit();
        },
        // 更新图片
        updateCropper () {
          this.$refs.fileUpload.$children[0].$el.click();
        },
        // 关闭窗口
        closeDialog () {
          this.showCropper = false;
        }
      }
    };
    </script>
    
    <style lang="scss" scoped>
    .UploadImg {
      .video-image {
        display: flex;
        figure {
           100px;
          img {
             100%;
            display: block;
          }
        }
      }
    }
    </style>

    封装裁剪组件 cropper.vue

    <template>
      <div :class="$options.name">
        <el-dialog
          :visible.sync="dialogVisible"
          width="600px"
          :before-close="handleClose">
          <div
            class="cropper-container">
            <div class="cropper-el">
              <vue-cropper
                ref="cropper"
                :img="cropperImg"
                :output-size="option.size"
                :output-type="option.outputType"
                :info="true"
                :full="option.full"
                :can-move="option.canMove"
                :can-move-box="option.canMoveBox"
                :fixed-box="option.fixedBox"
                :original="option.original"
                :auto-crop="option.autoCrop"
                :auto-crop-width="option.autoCropWidth"
                :auto-crop-height="option.autoCropHeight"
                :center-box="option.centerBox"
                :high="option.high"
                :info-true="option.infoTrue"
                @realTime="realTime"
                :enlarge="option.enlarge"
                :fixed="option.fixed"
                :fixed-number="option.fixedNumber"
              />
            </div>
            <!-- 预览 -->
            <div
              class="prive-el">
              <div
                class="prive-style"
                :style="{'width': '150px', 'height': '266px', 'overflow': 'hidden', 'margin': '0 25px', 'display':'flex', 'align-items' : 'center'}">
                <div
                  class="preview"
                  :style="previews.div">
                  <img
                    :src="previews.url"
                    :style="previews.img">
                </div>
              </div>
              <el-button
                @click="uploadBth"
                v-if="option.img">重新上传</el-button>
            </div>
          </div>
          <span
            slot="footer"
            class="dialog-footer">
            <el-button
              @click="handleClose">取 消</el-button>
            <el-button
              type="primary"
              @click="saveImg">确 定</el-button>
          </span>
        </el-dialog>
      </div>
    </template>
    
    <script>
    import { VueCropper } from 'vue-cropper';
    export default {
      name: 'Cropper',
      components: {
        VueCropper
      },
      props: {
        dialogVisible: {
          type: Boolean,
          default: false
        },
        imgType: {
          type: String,
          default: 'blob'
        },
        cropperImg: {
          type: String,
          default: ''
        }
      },
      data () {
        return {
          previews: {},
          option: {
            img: '', // 裁剪图片的地址
            size: 1, // 裁剪生成图片的质量
            full: false, // 是否输出原图比例的截图 默认false
            outputType: 'png', // 裁剪生成图片的格式 默认jpg
            canMove: false, // 上传图片是否可以移动
            fixedBox: false, // 固定截图框大小 不允许改变
            original: false, // 上传图片按照原始比例渲染
            canMoveBox: true, // 截图框能否拖动
            autoCrop: true, // 是否默认生成截图框
            // 只有自动截图开启 宽度高度才生效
            autoCropWidth: 200, // 默认生成截图框宽度
            autoCropHeight: 150, // 默认生成截图框高度
            centerBox: true, // 截图框是否被限制在图片里面
            high: false, // 是否按照设备的dpr 输出等比例图片
            enlarge: 1, // 图片根据截图框输出比例倍数
            mode: 'contain', // 图片默认渲染方式
            maxImgSize: 2000, // 限制图片最大宽度和高度
            limitMinSize: [100, 120], // 更新裁剪框最小属性
            infoTrue: false, // true 为展示真实输出图片宽高 false 展示看到的截图框宽高
            fixed: true, // 是否开启截图框宽高固定比例  (默认:true)
            fixedNumber: [9, 16] // 截图框的宽高比例
          }
        };
      },
      methods: {
        // 裁剪时触发的方法,用于实时预览
        realTime (data) {
          this.previews = data;
        },
        // 重新上传
        uploadBth () {
          this.$emit('update-cropper');
        },
        // 取消关闭弹框
        handleClose () {
          this.$emit('colse-dialog', false);
        },
        // 获取裁剪之后的图片,默认blob,也可以获取base64的图片
        saveImg () {
          if (this.imgType === 'blob') {
            this.$refs.cropper.getCropBlob(data => {
              this.$emit('upload-img', data);
            });
          } else {
            this.$refs.cropper.getCropData(data => {
              this.uploadFile = data;
              this.$emit('upload-img', data);
            });
          }
        }
      }
    };
    </script>
    
    <style lang="scss" scoped>
    .Cropper {
      .cropper-el {
        height: 300px;
         300px;
      }
      .cropper-container {
        display: flex;
        justify-content: space-between;
        .prive-el {
          height: 164px;
           94px;
          flex: 1;
          text-align: center;
          .prive-style {
            margin: 0 auto;
            flex: 1;
            -webkit-flex: 1;
            display: flex;
            display: -webkit-flex;
            justify-content: center;
            -webkit-justify-content: center;
            overflow: hidden;
            background: #ededed;
            margin-left: 40px;
          }
          .preview {
            overflow: hidden;
          }
          .el-button {
            margin-top: 20px;
          }
        }
      }
    }
    </style>

    效果截图

     问题总结

     问题一、如何阻止upload上传完之后就上传?

      将el-upload 的 auto-upload 设置为 false即可

    问题二、如何将获取到文件传给vue-cropper?

      vue-cropper 可以接受一个 blob,此时需要 new FileReader(),参考 MDN

    问题三、el-upload 选择完文件后不能更改,如何上传裁剪之后的图片?

      此问题在网上查到两种思路:

        1. 使用 this.$refs.fileUpload.$children[0].post(files) 方法可以更改上传的文件,调用此方法就会自动触发文件上,不用在调用submit,但是el-upload内部会报个错,file.status is not defined,并且不会触发before-upload和onsuccess,无法拿到上传之后的结果,具体原因没细查。

        2. 使用自定义上传,点击上传时直接调用submit 方法,这时会自动触发http-request中的自定义方法,可以拿到file中的所有属性,在函数里面使用 axios 自定义上传参数和文件。此方法比较好控制,本文也是采用的次方法进行上传。

    完整代码

    https://github.com/Shenjieping/cropper

    参考

    官方example源代码:https://github.com/xyxiao001/vue-cropper/blob/master/example/src/App.vue

    掘金:Vue+element-ui图片上传剪裁组件

  • 相关阅读:
    ajax上传文件
    nginx location指令详解
    总结php删除html标签和标签内的内容的方法
    useBuiltIns: 'usage'
    uni-app如何页面传参数的几种方法总结
    基于 schema 的数据校验
    canvas时点击事件和长按冲突
    vue 下载文件流,后台是get方式 ,并且导出出现excel乱码问题
    uni-app canvas 实现文字居中
    git reflog 回退
  • 原文地址:https://www.cnblogs.com/shenjp/p/13053026.html
Copyright © 2011-2022 走看看