el-upload手动上传图片的坑

需求:选取图片后,前端回显但不上传(不下载不入库),可修改删除,每次只允许上传一张图片,点击上传按钮再上传到服务器。
在这里插入图片描述
在这里插入图片描述

elementUI的坑:
1、官网给的大部分例子都是选图片后就直接上传,:before-upload方法定义上传文件前的钩子,在你选完图片后,就调用这个方法进行图片类型、大小等的判断,但如果你想让图片回显和上传动作分开的话需要设置:auto-upload="false"关闭文件自动上传,但是关闭后发现不会触发before-upload方法,再次但是当你手动上传执行this.$refs.upload.submit();这个方法时,才触发了before-upload上传前的钩子。
这个坑已经有解决方法了:用onChang方法

2、使用this.$refs.upload.clearFiles();清空文件列表,实现覆盖文件上传,但是会导致this.$refs.upload.submit();无效 (解决方法:去掉limit限制个数,通过fileList.splice(0,1) 每次取图片列表里最新的图片)

在这里插入图片描述

	  // 文件发生变化时的钩子
      changePictureUpload(file) {
        this.$refs.upload.clearFiles(); // 每次清空文件列表,就可以实现覆盖上传图片,但是只要有这行代码 this.$refs.upload.submit();就会失效。或者自己定义一个上传文件列表,清空文件列表也会使this.$refs.upload.submit();失效
       ...
      },
      // 自定义的上传方法
      myUpload(val) {... },
      onSubmit(file) {
        console.log("file", file)
        this.$refs.upload.submit(); // 此时调用myUpload()方法
      },

以解决:
完整代码:

<el-form-item label="上传图片:" prop="url">
                <el-upload
                  ref="upload"
                  class="pic-uploader"
                  action="https://jsonplaceholder.typicode.com/posts/"
                  :auto-upload="false"
                  :show-file-list="false"
                  :http-request="myUpload"
                  :on-change="changePictureUpload"
                >
                  <img v-if="tempPic" :src="tempPic" class="picture">
                  <i v-else class="el-icon-plus pic-uploader-icon"></i>
                </el-upload>
                <el-col :span="24">
                  <span class="text_tip">允许上传图片格式:png/jpg,且图片大小不能超过2MB</span>
                </el-col>
              </el-form-item>
methods: {
      //文件发生变化时的钩子
      changePictureUpload(file,fileList) {
        if (fileList.length > 1) {
          fileList.splice(0,1)
        }
        // this.$refs.upload.clearFiles();
        this.picInfo.name = file.raw.name.split(".")[0];
        this.picInfo.type = file.raw.name.split(".")[1];
        const isJPG = file.raw.type === 'image/jpeg';
        const isPNG = file.raw.type === 'image/png';
        const isLt2M = file.raw.size / 1024 / 1024 < 2;
        this.tempPic = URL.createObjectURL(file.raw);
        if (!isJPG && !isPNG) {
          this.$message.error('上传图片格式不符合条件!');
          this.tempPic = ''
          this.picInfo.name = ''
          this.picInfo.type = ''
        }
        if (!isLt2M) {
          this.$message.error('上传图片大小不能超过 2MB!');
          this.tempPic = ''
          this.picInfo.name = ''
          this.picInfo.type = ''
        }
        // 返回图是jpg或png格式并且大小不超过2MB
        return (isJPG || isPNG) && isLt2M;
      },
      // 自定义的上传方法
      // 请求后台把图片上传到服务器,返回图片地址
      myUpload(val) {
        this.$nextTick(async () => {
          // 以文件的格式传参
          let fd = new FormData();
          fd.append('file', val.file)
          let params = {
            url: '/fileUpload/pic', 
            param: fd
          }
          let res = await this.$store.dispatch('http/fileUpload', params)
          console.log("res", res)
          // 上传成功 返回码200 
          if(res.code==200){
            this.picInfo.url = res.data
       		// 把图片地址入库保存
            this.addPicInfo()
          }else{
            this.tempPic = ''
            this.$message({message:'上传失败,请重新选择图片' ,type:'error'})
          }
        })
      },
      onSubmit() {
        if (this.tempPic!= '') {
          this.$refs.upload.submit();
        } else {
          this.$message({message: '请上传图片', type: 'error'})
          return false
        }
      },
      //保存图片信息
      addPicInfo(){
        this.$nextTick(async ()=>{
          let params={
            className:'Carousel',
            method:'uploadCarousel',
            param:this.picInfo
          }
          let res = await this.$store.dispatch('http/post',params)
          if(res.code ==200){
            this.$message({message: '提交成功', type: 'success'})
            this.goBack()
          }
        })
      },
    }
  • 6
    点赞
  • 31
    收藏
    觉得还不错? 一键收藏
  • 3
    评论
el-upload 是一个 Element UI 提供的组件,可以用来上传文件,其中也包括图片。在手动上传图片时,可以使用以下步骤: 1. 在模板中使用 el-upload 组件,并设置相应的属性: ```html <el-upload class="upload-demo" action="/upload" :on-success="handleSuccess" :before-upload="beforeUpload" :show-file-list="false"> <el-button size="small" type="primary">点击上传</el-button> <div slot="tip" class="el-upload__tip">只能上传jpg/png文件,且不超过500kb</div> </el-upload> ``` 其中,`action` 属性指定了上传文件的 URL,`on-success` 属性指定了上传成功后的回调函数,`before-upload` 属性指定了上传前的处理函数,`show-file-list` 属性设置为 `false`,表示不展示已上传的文件列表。 2. 在 Vue 实例中定义相应的方法: ```javascript export default { methods: { handleSuccess(response, file, fileList) { console.log(response, file, fileList); }, beforeUpload(file) { const isJPG = file.type === 'image/jpeg' || file.type === 'image/png'; const isLt2M = file.size / 1024 / 1024 < 2; if (!isJPG) { this.$message.error('上传头像图片只能是 JPG 格式!'); } if (!isLt2M) { this.$message.error('上传头像图片大小不能超过 2MB!'); } return isJPG && isLt2M; }, }, }; ``` `handleSuccess` 方法会在上传成功后被调用,参数 `response` 表示服务端返回的数据,`file` 表示当前上传的文件,`fileList` 表示已上传的文件列表。 `beforeUpload` 方法会在上传前被调用,参数 `file` 表示当前要上传的文件。在该方法中,可以进行文件类型、大小等的校验。如果校验不通过,可以通过 `this.$message.error` 方法弹出错误提示。 注意:以上代码中的 `this.$message` 是 Element UI 提供的消息提示组件,需要在 Vue 实例中进行注册。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值