element ui 的 el-upload上传功能记录

auto-upload为false的时候 before-upload和http-request 是无效的

可以使用 on-change 方法 限制文件的大小和格式

html

<el-upload class="avatar-uploader" action="" list-type="picture-card" :limit="5" :auto-upload="false" :file-list="fileList" :on-change="handleChange" :on-remove="handleRemove" :class="{ hide: hideUploadEdit }">

<i class="el-icon-plus"></i>

<div slot="tip" class="el-upload__tip">

限上传png、jpg、jepg格式的图片,大小不超过5M,最多上传5张

</div>

</el-upload>

js

handleChange(file, fileList) {
      //图片格式限制
      const isJPG = file.raw.type === 'image/jpeg';
      const isPNG = file.raw.type === 'image/png';
      if (!isJPG && !isPNG) {
        this.$message.error('上传图片只能是 png、jpg、jepg 格式!');
        fileList.splice(-1, 1);  // 图片不在列表显示
        return
      }

      // 图片大小的限制
      const isLt5M = file.raw.size / 1024 / 1024 < 5;
      if (!isLt5M) {
        this.$message.error('上传图片大小不能超过5MB!');
        fileList.splice(-1, 1); 
        return
      }

      uploadImg(file.raw).then(res => {
        this.imgList.push(res)
        this.fileList = JSON.parse(JSON.stringify(fileList))
        this.hideUploadEdit = this.fileList.length >= 5
        this.form.imgUrl = this.imgList.join(',')
      }).catch(err => {
        fileList.splice(-1, 1);
      })
},

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Element UIel-upload组件可以用于文件上传,并且支持文件预览功能。在使用el-upload组件时,你可以通过设置属性来启用文件预览功能。 首先,确保你已经正确引入了Element UI库和el-upload组件。然后,在你的代码中使用el-upload组件,并设置以下属性: 1. 设置`action`属性为文件上传的接口地址。 2. 设置`show-file-list`属性为`false`,以隐藏默认的文件列表展示。 3. 设置`on-success`属性为一个回调函数,用于处理文件上传成功后的逻辑。 4. 设置`before-upload`属性为一个回调函数,用于在文件上传之前进行一些操作,比如文件预览。 5. 在`before-upload`回调函数中,可以通过`file`参数获取到当前上传的文件对象。你可以使用`FileReader`对象来读取文件内容,并将其显示在页面上。 下面是一个示例代码: ```html <template> <el-upload class="upload-demo" action="/your-upload-api" :show-file-list="false" :before-upload="handleBeforeUpload" :on-success="handleSuccess" > <el-button size="small" type="primary">点击上传</el-button> </el-upload> </template> <script> export default { methods: { handleBeforeUpload(file) { // 使用FileReader读取文件内容并显示预览 const reader = new FileReader(); reader.onload = (e) => { // 在页面上显示文件预览 const preview = document.createElement('img'); preview.src = e.target.result; document.body.appendChild(preview); }; reader.readAsDataURL(file); // 返回false以阻止文件上传 return false; }, handleSuccess(response) { // 文件上传成功后的处理逻辑 console.log('文件上传成功', response); }, }, }; </script> ``` 这样,当用户选择文件后,会触发`before-upload`回调函数,你可以在该函数中读取文件内容并显示预览。然后,文件会被阻止上传,直到你处理完预览逻辑后再手动触发文件上传。 希望以上信息对你有帮助!

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值