用element-ui进行文件的上传

在进项的项目中,我使用vue配合element搭建的项目,如今须要用到上传文件的写法!如今列举下个人项目中所使用的上传文件的方法!html

            <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来进行手动的处理。在上传前也可将对应的上传的文件显示出来,对文件大小作限制。记得,当你的文件为空时也会本身上传的。vue

  

 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,在对其进行添加你所须要上传的参数,接着走接口请求就能够将你的文件上传成功!app

  上传的方式多种多样,你能够本身参考element的文档来进行,固然里面的参数添加和个人这种是同样的!你也能够本身运用h5本身来写一个上传文件的组件,利用filereader来完成this

相关文章
相关标签/搜索