用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

相關文章
相關標籤/搜索