使用element中的携带参数的多图片上传

使用element中的携带参数的多图片上传


提示:写完文章后,目录可以自动生成,如何生成可参考右边的帮助文档

 

文章目录

 


前言

写过很多次文件上传,每次重新写还是会遇到各种问题,特意记录一下这次写的文件上传,方便下次作为参考。


 

一、要做的效果图

使用element中的携带参数的多图片上传

二、使用步骤

1.template代码

代码如下(示例):

<el-form-item label="预览图片" prop="imagelist">

        <el-upload

          :action="form.uploadUrl"

          list-type="picture-card"

          :file-list="ruleForm.imagelist"

          :http-request="imageChange"

          :on-preview="handlePictureCardPreview"

          :on-remove="handleRemoveImg"

          :before-upload="beforeImgUpload"

          :on-change="uploadImgChange"

          ref="uploadImg"

        >

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

        </el-upload>

        <el-dialog :visible.sync="dialogVisible">

          <img width="100%" :src="dialogImageUrl" alt />

        </el-dialog>

      </el-form-item>

2.声明变量

代码如下(示例):

使用element中的携带参数的多图片上传

3.上传文件的方法

代码如下(示例):

//图片上传

    // 图片展示上传

    handleRemoveImg(file, fileList) {

      for (var i in this.ruleForm.imagelist) {

        if (file.uid == this.ruleForm.imagelist[i].uid) {

          this.ruleForm.imagelist.splice(i, 1);

        }

      }

    },

      //文件状态改变时的钩子

    uploadImgChange(file, fileList) {

      this.ruleForm.imagelist.push({

        name: file.name,

        url: file.url,

      });

    },

     //删除的弹框

    handlePictureCardPreview(file) {

      this.dialogImageUrl = file.url;

      this.dialogVisible = true;

    },

    beforeImgUpload(file, fileList) {

      let _this = this;

      //每次改变时,做检测

      let regs = /.+?(\.jpg|\.png|\.jpeg|\.gif)/g;

      let isImg = regs.test(file.name);

      if (!isImg) {

        this.$message.error("请上传正确的图片格式");

        return false;

      }

    },

    // 提交图片

    imageChange(param) {

      let _this = this;

      let formData = new FormData();

      formData.append("file", param.file);

      this.axios

        .post("/material/material/file/upload-img", formData)

        .then((res) => {

          let type;

          if (res.data.code == 200) {

            _this.previewImages.push(res.data.data.catalog);

 

            type = "success";

          } else {

            type = "error";

          }

          _this.$message({

            message: res.data.error,

            type: type,

          });

        });

    },


总结

提示:这里对文章进行总结:
该文章里面文件上传进行了传参。注意:数据回显的时候,图片上传的list集合一定要有name,url参数,否则图片缩略图不会显示。