用element-ui进行文件的上传

在进项的项目中,我使用vue配合element搭建的项目,现在需要用到上传文件的写法!现在列举下我的项目中所使用的上传文件的方法!

            <el-upload
              style="display:inline-block"
              :limit="1"
              class="upload-demo"
              ref="upload"
              accept=".xls,.xlsx"
              action="/hqx/knowledge/importKnowledge"
              :file-list="fileList"
              :http-request="uploadSectionFile"
              :auto-upload="false">
              <el-button slot="trigger" size="small" type="primary" plain>选取文件</el-button>
              <el-button style="margin-left: 10px;" size="small" icon="el-icon-upload2" type="success" @click="submitUpload">导入</el-button>
            </el-upload>

  上传文件有多重方式来进行,这里叙述下手动上传的方法,并且用了请求的拦截。如果你的上传不需要其他的参数,那么你可以直接通过action填写上传地址来进行,如果需要进行参数的处理,那么你就需要添加http-request来进行手动的处理。在上传前也可将对应的上传的文件显示出来,对文件大小做限制。记得,当你的文件为空时也会自己上传的。

  

 submitUpload() {
        let list = document.getElementsByClassName('el-upload-list__item is-ready')
        if(list.length == 0){
          this.$message({
            type:'warning',
            message:"请选择需要导入的模板!"
          })
          return;
        }
        this.$refs.upload.submit();
      },
      uploadSectionFile(param){
        var fileObj = param.file;
        // FormData 对象
        var form = new FormData();
        // 文件对象
        form.append("file", fileObj);
        form.append("userId", this.userId);
        form.append("userName", this.userName);
        this.GLOBAL.POST('/hqx/knowledge/importKnowledge',form).then(res => {
          if(res.data.success == true){
            this.$message({
              type:'success',
              message:res.data.msg
            })
            this.fileList =[]
          } else {
            this.$message({
              type:'success',
              message:res.data.msg
            })
             this.fileList =[]
          }
        })
      },

  文件的上传都是通过form表单来进行的,所以和原生的上传一样,我们可以new一个formdata对象来获取上传的form,在对其进行添加你所需要上传的参数,接着走接口请求就可以将你的文件上传成功!

  上传的方式多种多样,你可以自己参考element的文档来进行,当然里面的参数添加和我的这种是一样的!你也可以自己运用h5自己来写一个上传文件的组件,利用filereader来完成

原文地址:https://www.cnblogs.com/xieyong25/p/9753393.html