element-ui图片上传组件之限制每次5张上传(或者自定义每次几张上传)

20 篇文章 1 订阅

element-ui图片上传组件——限制每次5张上传

1、limit上传个数限制配合on-exceed属性使用;
2、上传之前提示图片大小限制属性before-upload;
3、上传成功后对图片的filelist处理;
4、使用oss上传,没使用elementui的上传方式;

直接上代码

<template>
  <div class="ele-upload-styl">
    <el-upload
      action=""
      :headers="uploadProps.headers"
      :show-file-list="false"
      :http-request="fnUploadRequest"
      :on-success="handleSuccess"
      :before-upload="handleUpload"
      accept=".png,.jpg,.jpeg,.gif,.webp"
      multiple
      :limit="5"
      :on-exceed="handleExceed"
      ref="upload"
    >
      <div class="img-cont pr">
        <img slot="trigger" class="img-icon" src="@/assets/img/icon-img-upload.png" alt="">
        <span slot="tip" class="img-text">图片</span>
      </div>
    </el-upload>
  </div>
</template>

<script>
import {getAccessToken,getRefreshToken,getAccessTokenTTL,} from "@/utils/auth";
import { uploadOSS } from '@/utils/ossImage';

export default {
  name: "imgUpload",
  components: {},
  props: {},
  computed: {
    userAccountID() {
      return this.$store.state.user.userAccountID;
    },
    uploadProps() {
      return {
        // action: `${process.env.VUE_APP_BASE_API}/api/image/upload`,
        headers: {
          // 接口可能要带token: "",
          Authorization: getAccessToken(),
        },
        data: {},
      };
    },
  },
  data() {
    return {};
  },
  methods: {
    // handleExceed(file, fileList) {
    //   // console.log(file, fileList);
    //   this.$message.error("上传失败,限制上传数量10张图片以内!");
    // },
    // beforeUpload_u(file, fileList) {
    //   // console.log(file, fileList);
    //   var testmsg = file.name.substring(file.name.lastIndexOf(".") + 1);
    //   const extension =
    //     testmsg === "png" ||
    //     testmsg === "jpg" ||
    //     testmsg === "jpeg" ||
    //     testmsg === "gif" ||
    //     testmsg === "webp";
    //   const isLimit10M = file.size / 1024 / 1024 < 10;
    //   var bool = false;
    //   if (extension && isLimit10M) {
    //     bool = true;
    //   } else {
    //     bool = false;
    //   }
    //   if (!extension) {
    //     this.$message.error("请上传图片格式文件!");
    //     return bool;
    //   }
    //   if (!isLimit10M) {
    //     this.$message.error("上传失败,不能超过10M!");
    //     return bool;
    //   }
    //   return bool;
    // },
    // handleSuccess(res) {
    //   // console.log(res);
    //   if (res.code == 0) {
    //     this.$emit("imgData", res.item);
    //     this.$message.success("上传图片成功!");
    //   } else {
    //     this.$message.error("上传图片失败!");
    //   }
    // },
    // handleError(err) {
    //   this.$message.error("上传图片失败!");
    // },

    // 上传图片判断
    handleUpload(file) {
      // console.log(file);
      var testmsg = file.name.substring(file.name.lastIndexOf(".") + 1);
      const extension =
        testmsg.toLowerCase() === "png" ||
        testmsg.toLowerCase() === "jpg" ||
        testmsg.toLowerCase() === "jpeg" ||
        testmsg.toLowerCase() === "gif" ||
        testmsg.toLowerCase() === "webp";

      const isLimit10M = file.size / 1024 / 1024 < 10;
      var bool = false;
      if (extension && isLimit10M) {
        bool = true;
      } else {
        bool = false;
      }
      if (!extension) {
        this.$message.error("请上传图片格式文件!");
        return bool;
      }
      if (!isLimit10M) {
        this.$message.error("文件太大,单个文件不能超过10M! ");
        return bool;
      }
      return bool;
    },
    handleExceed(files, fileList) {
      // console.log(files, fileList);
      this.$message.warning(` 一次最多上传5张,请分批次上传! `)
    },
    // 上传图片
    async fnUploadRequest(options) {
      // console.log(options);
      try {
        this.$loading.show()
        // console.log(options);
        let file = options.file; // 拿到 file
        let res = await uploadOSS(file)
        // console.log(res);
        // 返回的就是图片地址
        this.$emit("imgData", res);
        this.$loading.hide()
      } catch (e) {
        this.$loading.hide()
        this.$message.error("上传图片失败!请重新上传");
      }
    },
    //图片上传成功回调
    handleSuccess(res) {
      // console.log(res);
      this.$refs.upload.clearFiles() //清除图片列表
    },
  },
};
</script>
<style  lang="scss" scoped>
::v-deep .el-upload,
::v-deep .el-upload--picture-card {
  // width: 50px;
  height: 24px;
  border: none;
  line-height: 0;
  display: block;
  background: #f5f6fb;
}
::v-deep .el-upload {
  width: 50px;
}
.img-cont {
  width: 50px;
  height: 24px;
  background: #f5f6fb;
  .img-icon {
    color: #ccc;
  }
  .img-text {
    font-size: 12px;
    height: 24px;
    color: #000;
    margin-left: 3px;
  }
}
</style>

其中的一些参数打印
在这里插入图片描述

重点是这句代码:每次成功后都清空数据列表

this.$refs.upload.clearFiles() //清除列表

在这里插入图片描述

  • 3
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
1. 首先,在项目中安装element-ui和axios: ``` npm install element-ui axios --save ``` 2. 在main.js中引入element-ui和axios: ``` import Vue from 'vue' import ElementUI from 'element-ui' import 'element-ui/lib/theme-chalk/index.css' import axios from 'axios' Vue.use(ElementUI) Vue.prototype.$axios = axios ``` 3. 在组件中使用上传组件: ``` <template> <div> <el-upload class="avatar-uploader" action="/api/upload" :show-file-list="false" :on-success="handleSuccess" :before-upload="beforeUpload" > <img v-if="imageUrl" :src="imageUrl" class="avatar"> <i v-else class="el-icon-plus avatar-uploader-icon"></i> </el-upload> </div> </template> ``` 4. 在组件中定义上传前和上传成功的方法: ``` <script> export default { data() { return { imageUrl: '' } }, methods: { beforeUpload(file) { const isJPG = file.type === 'image/jpeg' const isPNG = file.type === 'image/png' if (!isJPG && !isPNG) { this.$message.error('只能上传jpg或png格式的图片') return false } const isLt2M = file.size / 1024 / 1024 < 2 if (!isLt2M) { this.$message.error('上传的图片大小不能超过2MB') return false } return true }, handleSuccess(response) { this.imageUrl = response.data.url } } } </script> ``` 5. 在服务器端,需要接收上传的图片,并将其保存到指定路径: ``` const express = require('express') const multer = require('multer') const path = require('path') const app = express() const storage = multer.diskStorage({ destination: function (req, file, cb) { cb(null, path.join(__dirname, '/public/images')) }, filename: function (req, file, cb) { const extname = path.extname(file.originalname) cb(null, Date.now() + extname) } }) const upload = multer({ storage: storage }) app.post('/api/upload', upload.single('file'), (req, res) => { const url = `http://localhost:3000/images/${req.file.filename}` res.json({ code: 0, data: { url: url } }) }) app.listen(3000, () => { console.log('server is running at http://localhost:3000') }) ``` 以上就是在Vue中使用element-ui上传组件上传图片的方法。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值