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>

 

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