用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來完成

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM