Vue上傳文件:ElementUI中的upload實現


一、上傳文件實現

  兩種實現方式:

1、直接action

<el-upload

 class="upload-file"
  drag
  :action="doUpload"
  :data="pppss">
  <i class="el-icon-upload"></i>
  <div class="el-upload__text">將文件拖到此處,或<em>點擊上傳</em></div>
</el-upload>

  :action,必選參數,上傳的地址,String類型。data()需要使用代理轉發,要不然會有跨域的問題

  :data,上傳時附帶的額外參數,object類型。用於傳遞其他的需要攜帶的參數,比如下面的srid

data(){

    return {
        ,doUpload:'/api/up/file'
        ,pppss:{
            srid:''
        }
    }
},

2、利用before-upload屬性

  此種方式有個弊端,就是action是必選的參數,那么action如果和posturl一致,總會請求2次,所以一般把action隨便寫一個url,雖然不影響最終效果,但是這樣會在控制台總有404錯誤報出

<el-upload

 class="upload-file"
  drag
  :action="doUpload"
  :before-upload="beforeUpload"
 ref="newupload"
  multiple
  :auto-upload="false">
  <i class="el-icon-upload"></i>
  <div class="el-upload__text">將文件拖到此處,或<em>點擊上傳</em></div>
</el-upload>

beforeUpload(file){

    let fd = new FormData();
    fd.append('file',file);//傳文件
    fd.append('srid',this.aqForm.srid);//傳其他參數
    axios.post('/api/up/file',fd).then(function(res){
            alert('成功');
    })
},
newSubmitForm(){//確定上傳
    this.$refs.newupload.submit();
}

二、常用方法介紹

1、動態改變action地址

  action是一個必填參數,且其類型為string,我們把action寫成:action,然后后面跟着一個方法名,調用方法,返回你想要的地址,實現動態的去修改上傳地址

//html 代碼

<el-upload  :action="UploadUrl()"  :on-success="UploadSuccess" :file-list="fileList">
    <el-button size="small" type="primary" >點擊上傳</el-button>
</el-upload>
 
// js 代碼在 methods中寫入需要調用的方法
methods:{
    UploadUrl:function(){
        return "返回需要上傳的地址";     
    }   
}   

2、在文件上傳前做類型大小等限制

1)一種方式是,加accpet屬性

<el-upload class="upload-demo" :multiple="true" :action="action" accept="image/jpeg,image/gif,image/png,image/bmp" 
:file-list="fileList" :before-upload="beforeAvatarUpload" :on-success="handleAvatarSuccess">

2)另一種方式是在上傳前的觸發函數里面去判斷

beforeAvatarUpload(file) {

    const isJPG = file.type === 'image/jpeg';
    const isGIF = file.type === 'image/gif';
    const isPNG = file.type === 'image/png';
    const isBMP = file.type === 'image/bmp';
    const isLt2M = file.size / 1024 / 1024 < 2;
 
    if (!isJPG && !isGIF && !isPNG && !isBMP) {
        this.common.errorTip('上傳圖片必須是JPG/GIF/PNG/BMP 格式!');
    }
    if (!isLt2M) {
        this.common.errorTip('上傳圖片大小不能超過 2MB!');
    }
    return (isJPG || isBMP || isGIF || isPNG) && isLt2M;
},

3、同時傳遞form表單及有多個upload文件該如何傳遞

newSubmitForm () {

 this.$refs['newform'].validate((valid) => {
    if (valid) {
      //表單的數據
      this.uploadForm.append('expName', this.newform.expName)
      this.uploadForm.append('expSn', this.newform.expSn)
      this.uploadForm.append('groupId', this.newgroupId)
      this.uploadForm.append('subGroupId', this.newsubgroupId)
      this.uploadForm.append('expvmDifficulty', this.newform.expvmDifficulty)
      
      newExp(this.uploadForm).then(res => {
        if (res.code === 400) {
          this.$message.error(res.error)
        } else if (res.code === 200) {
          this.$message.success('上傳成功!')
        
        }
      })
      this.$refs.uploadhtml.submit()   // 提交時分別觸發各上傳組件的before-upload函數
      this.$refs.uploadfile.submit()
      this.$refs.uploadvideo.submit()   
    } else {
      console.log('error submit!!')
      return false
    }
  })
},
newHtml (file) {   // before-upload
 this.uploadForm.append('html', file)
 return false
},
newFiles (file) {
 this.uploadForm.append('file[]', file)
 return false
},
newVideo (file) {
 this.uploadForm.append('video', file)
 return false
}
export function newExp (data) {
 return axios({
    method: 'post'// 方式一定是post
    url: '你的后台接收函數路徑',
    timeout: 20000,
    data: data        // 參數需要是單一的formData形式
  })
}

  注意:(1)對於多個上傳組件來說,需要分別觸發,去給FormData append數據

  (2)接收多文件一定要是數組形式的file[]this.uploadForm.append('file[]', file)

4、如何傳遞文件和其他參數

  就像第一節那樣,如果不使用action實現上傳,而使用before-upload屬性也能實現上傳的效果。

  before-upload屬性,這是一個function類型的屬性,默認參數是當前文件,只要能傳遞這個文件也能實現效果

  要傳遞這個方法就需要new一個formdata對象,然后對這個對象追加keyvalue,類似於postman測試時那樣。

  另外注意:傳遞formdatadata不能一起傳遞,要傳遞formdata就不能有data,所以對於其他參數的傳遞,也要改為

beforeUpload (file,id) {

    let fd = new FormData()
    fd.append('file', file)
    fd.append('id',id)//其他參數
    axios.post(url, fd, {
         
    })
 },

  而不能使用這種又有FormData,又有data的模式

beforeUpload (file,id) {

        let fd = new FormData()
        fd.append('key', file, fileName)
        axios.post(url, fd,{
          data:{
           id:id
          },
          headers: {
           'Content-Type': 'multipart/form-data'
          }
        })
     },


    DEMO下載地址:https://dwz.cn/fgXtRtnu 


免責聲明!

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



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