首页 > 其他分享 >vue2 +element-ui图片上传示例

vue2 +element-ui图片上传示例

时间:2024-04-02 17:23:44浏览次数:10  
标签:el 截图 false 示例 fileList element ui file true

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

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>

 

标签:el,截图,false,示例,fileList,element,ui,file,true
From: https://www.cnblogs.com/btsn/p/18111056

相关文章

  • C#将dataguidview与excel数据互相读写
    库需求需要NPOI库(处理Excel表格库)可在vs工具菜单栏中的NuGet包管理器中搜索NPOI下载·获得效果简单预览读点击查看代码privatevoidbtnRead_Click_1(objectsender,EventArgse){#region打开对话框,自定义选择要读取excel表格路径......
  • ES6 reduce方法:示例与详解、应用场景
    还是大剑师兰特:曾是美国某知名大学计算机专业研究生,现为航空航海领域高级前端工程师;CSDN知名博主,GIS领域优质创作者,深耕openlayers、leaflet、mapbox、cesium,canvas,webgl,echarts等技术开发,欢迎加底部微信(gis-dajianshi),一起交流。No.内容链接1Openlayers【入门教程】-......
  • 鸿蒙HarmonyOS实战-ArkUI组件(Radio)
    ......
  • 前端学习-UI框架学习-Bootstrap5-015-列表组
    菜鸟教程链接列表组+active激活+disabled禁用要创建列表组,可以在元素上添加.list-group类,在元素上添加.list-group-item类:<template><divclass="containermt-3"><h2>列表组</h2><p>列表组+active激活+disabled禁用</p><......
  • gem5 CPU ISA level is lower than required
    错误提示:/lib/x86_64-linux-gnu/libc.so.6:CPUISAlevelislowerthanrequired错误截图:在互联网上搜索该错误,在gem5的邮件列表发现:Jason说在某次commit解决了这个问题,然后去这两个链接里面看一下:大概的意思是说GLIBC更新了,对硬件检查更严格了。当尝试加载动态......
  • 【魔改bkui】使用bkui过程中的抓马瞬间
    本文来自腾讯蓝鲸智云社区用户:kai索引0前言1"魔改"支持自定义输入的select前情提要“魔改”第一步——找回组件的灵魂“魔改”第二步——用户体验up?“魔改”第三步——做icon里最靓的仔“魔改”第四步——拗不过的"甲方dad"2TheEnd一些碎碎念前言众所周知,蓝......
  • docker-compose 部署OWASP Juice Shop + CTFd
    项目介绍1.OWASPJuiceShop原文OWASPJuiceShopisprobablythemostmodernandsophisticatedinsecurewebapplication!Itcanbeusedinsecuritytrainings,awarenessdemos,CTFsandasaguineapigforsecuritytools!JuiceShopencompassesvulnerabili......
  • Quill文档(四):使用Parchment克隆Medium
    为了提供一致的编辑体验,您需要一致的数据和可预测的行为。不幸的是,DOM缺乏这两个特性。现代编辑器的解决方案是维护自己的文档模型来表示它们的内容。对于Quill来说,Parchment就是这样的解决方案。它在自己的代码库中组织,并拥有自己的API层。通过Parchment,您可以定制Quill识别......
  • Quill文档(三):构建自定义模块
    Quill作为编辑器的核心优势在于其丰富的API和强大的定制能力。当您在Quill的API之上实现功能时,将其组织为一个模块可能会很方便。为了本指南的目的,我们将逐步介绍一种构建单词计数器模块的方法,这是许多文字处理器中常见的功能。注意在内部,模块是Quill的许多功能的组织方......
  • Cannot deserialize the current JSON array (e.g. [1,2,3]) into type ‘model’ bec
    错误:CannotdeserializethecurrentJSONarray(e.g.[1,2,3])intotype‘model’becausethetyperequiresaJSONobject(e.g.{“name”:“value”})todeserializecorrectly.TofixthiserroreitherchangetheJSONtoaJSONobject 原因:json或xml字符串中......