vue2 +element-ui图片上传示例

这里使用了一个没有用的裁剪插件,需要先下载它

npm i [email protected] --save

然后在main.js引入:

import VueCropper from 'vue-cropper'
Vue.use(VueCropper)

1、html部分:

<template>
    <el-form ref="form" :model="form" label-width="1.2rem">
        <el-form-item label="人员照片:" prop="avatar">
            <el-upload 
              ref="pic" 
              action="#" 
              :class="{ uploadBox_hide: isHideUploadBtn }"
              list-type="picture-card" 
              :auto-upload="false" 
              :file-list="fileList"
              :on-remove="handleRemove"
              :on-change="changeUpload">
              <i class="el-icon-plus"></i>
            </el-upload>
          </el-form-item>
    </el-form>
   <!-- vueCropper 剪裁图片实现-->
    <el-dialog title="图片剪裁" :visible.sync="showCropper" append-to-body :close-on-click-modal="false">
      <div class="cropper-content">
        <div class="cropper" style="text-align:center">
          <vueCropper ref="cropper" :img="option.img" :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>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button @click="showCropper = false">取 消</el-button>
        <el-button type="primary" @click="finish" :loading="btnLoading">确认</el-button>
      </div>
    </el-dialog>
</template>

2、js部分:

<script>
    import { uploadImage } from '@/api/index';
    export default {
       data() {
            return {
                form: {
                    avatar: "", // 人员照片
                },
                showCropper: false, // 是否显示图片裁剪弹窗
      option: {
        img: '', // 裁剪图片的地址
        info: true, // 裁剪框的大小信息
        outputSize: 1, // 裁剪生成图片的质量
        outputType: 'jpeg', // 裁剪生成图片的格式
        canScale: false, // 图片是否允许滚轮缩放
        autoCrop: true, // 是否默认生成截图框
        // autoCropWidth: 300, // 默认生成截图框宽度
        // autoCropHeight: 200, // 默认生成截图框高度
        fixedBox: false, // 固定截图框大小 不允许改变
        fixed: true, // 是否开启截图框宽高固定比例
        fixedNumber: [800, 800], // 截图框的宽高比例
        full: true, // 是否输出原图比例的截图
        canMoveBox: true, // 截图框能否拖动
        original: false, // 上传图片按照原始比例渲染
        centerBox: false, // 截图框是否被限制在图片里面
        infoTrue: true // true 为展示真实输出图片宽高 false 展示看到的截图框宽高
      },
      btnLoading: false,
      tempfileList: [],
      fileList: [],
      isHideUploadBtn: false, // 是否隐藏上传按钮
            }
       },
        methods: {
            // 图片上传
    changeUpload(file, fileList) {
      this.fileList = [];
      let passImgTypes = ['jpg','png','gif','jpeg'];
      let curImgType = file.name.substring(file.name.lastIndexOf('.') + 1)
      if (!passImgTypes.includes(curImgType)) {
        this.$message.error('上传头像图片只能是 JPG、PNG、GIF 或 JPEG 格式!');
        return
      }
      var reader = new FileReader();
      reader.readAsDataURL(file.raw);
      let data;
      reader.onload = e => {
        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.tempfileList = [];
        this.tempfileList.push({url: data }) // 暂时存储,裁剪后点击确定则赋值给 fileList
        this.isHideUploadBtn = fileList.length >= 1
      }
      this.$nextTick(() => {
        this.option.img = file.url; // 赋值给裁剪框的图片
        this.showCropper = true
      })
    },
    // 点击裁剪,这一步是可以拿到处理后的地址
    finish() {
      this.btnLoading = true;
      this.$refs.cropper.getCropBlob((data) => {
        const params = new FormData();
        params.append("file", data);
        params.append("secretFlag", 'Y');
        let loading = this.$loading({ lock: true, text: '正在导入...', spinner: 'el-icon-loading', background: 'rgba(0, 0, 0, 0.7)' });
// 以下是调用接口 uploadImage(params).then(res
=> { if (res.code == '00000') { console.log("上传图片成功-->>",res); this.fileList = this.tempfileList; // 赋值给 fileList,显示人员照片 this.form.avatar = res.data.fileId; } else { this.fileList = []; this.isHideUploadBtn = this.fileList.length >= 1; } loading.close(); this.btnLoading = false; }).catch(err => { this.$message.error(err.message) loading.close(); }) }) this.showCropper = false }, // 删除活动展示照片 handleRemove(file, fileList) { this.fileList = []; if (this.fileList.length === 0) { this.fileList = []; } else { let dl = this.fileList.indexOf(file); this.fileList.splice(dl, 1); } this.isHideUploadBtn = this.fileList.length >= 1; }, } } </script>

 3、css部分

<style lang="scss" scoped>
    /* 截图 */
.cropper {
  width: auto;
  height: 6rem;
}
.el-dialog__wrapper {
      top: -5rem;
    }
    .el-dialog {
      margin-top: 5vh !important;
    }

    .el-upload-list__item {
      transition: none !important;
    }
    .el-upload-list__item {
      width: 1.2rem;
      height: 1.2rem;
    }
    .el-upload--picture-card {
      width: 1.2rem;
      height: 1.2rem;
      display: flex;
      justify-content: center;
      align-items: center;
    }
    // 隐藏上传按钮
    .uploadBox_hide .el-upload--picture-card {
      display: none;
    }
    /* 隐藏上传成功的文件后面的绿色勾 */
    .el-upload-list__item.is-success .el-upload-list__item-status-label {
      display: none;
    }
</style>

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章