element-ui多文件上傳

上傳方案一:
先將文件上傳到七牛,再將七牛上傳返回的文件訪問路徑上傳到服務器數組

<div class="upload-music-container">
    <el-upload
      class="upload-music"
      ref="upload"
      action="http://up-z2.qiniup.com/"
      :data="{token:uploadToken}"
      multiple
      accept=".mp3"
      :before-upload="uploadBefore"
      :on-change="uploadChange"
      :on-success="uploadSuccess"
      :on-error="uploadError">
      <el-button size="small" type="primary">選取文件</el-button>
      <div slot="tip" class="el-upload__tip">僅支持上傳mp3文件,文件大小不超過500M</div>
    </el-upload>
    <el-button size="small" type="success" @click="submitUpload">上傳到服務器</el-button>
</div>
 

export default {
    name: 'uploadMusic',
    data() {
      return {
        headers: {},
        uploadToken: null,
        canUploadMore: true,
        fileList: null,
      }
    },
    created() {
      this.headers = {}     //此處須要與server約定具體的header
      this.getUploadToken()
    },
    methods: {
      //獲取上傳七牛token憑證
      getUploadToken() {
        this.$http.get('xxxxxxx', {headers: this.headers}).then(response => {
          if (response.data.status == 200) {
            let resp = response.data.data
            this.uploadToken = resp.token
          } else {
            this.$message({
              message: '獲取憑證失敗,請重試',
              type: 'error'
            })
          }
        })
      },
      //獲取音頻文件時長
      getVideoPlayTime(file, fileList) {
        let self = this
        //獲取錄音時長
        try {
          let url = URL.createObjectURL(file.raw);
          //經測試,發現audio也可獲取視頻的時長
          let audioElement = new Audio(url);
          let duration;
          audioElement.addEventListener("loadedmetadata", function (_event) {
            duration = audioElement.duration;
            file.duration = duration
            self.fileList = fileList
          });
        } catch (e) {
          console.log(e)
        }
      },
      //校驗上傳文件大小
      uploadChange(file, fileList) {
        this.fileList = fileList
        let totalSize = 0
        for (let file of fileList) {
          totalSize += file.raw.size
        }
        if (totalSize > 500 * 1024 * 1024) {
          this.canUploadMore = false
          this.$message({
            message: '上傳文件不能不超過500M',
            type: 'warn'
          })
        } else {
          this.canUploadMore = true
        }
      },
      uploadBefore(file) {
        if (this.canUploadMore) {
          return true
        }
        return false
      },
      //上傳成功
      uploadSuccess(response, file, fileList) {
        this.getVideoPlayTime(file, fileList)
      },
      //上傳失敗
      uploadError(err, file, fileList) {
        console.log(err)
      },
      //上傳服務器數據格式化
      getUploadMusicList() {
        let musicList = []
        for (let file of this.fileList) {
          if (file.response && file.response.key) {
            musicList.push({
              "play_time": file.duration,  //播放時長
              "size": file.size/1024,      //文件大小 單位 kb
              "song_name": file.name,      //歌曲名
              "voice_url": "xxxx"          //上傳七牛返回的訪問路徑
            })
          }
        }
        return musicList
      },
      //上傳至服務器
      submitUpload() {
        let musicList = this.getUploadMusicList()
        this.$http.post('xxxxxxxxxx', {music_list: musicList}, {headers: this.headers}).then(response => {
          if (response.data.status == 200) {
            this.$refs.upload.clearFiles() //上傳成功後清空文件列表
            this.$message({
              message: '上傳服務器成功',
              type: 'success'
            })
          } else{
            this.$message({
              message: '上傳服務器失敗,請重試',
              type: 'error'
            })
          }
        }).catch(err => {
          this.$message({
            message: '上傳服務器失敗,請重試',
            type: 'error'
          })
        })
      },
    }
  }

上傳方案二:
直接將文件上傳到服務器服務器

<div class="upload-music-container">
    <el-upload
      class="upload-music"
      ref="upload"
      multiple
      action=""
      :auto-upload="false"
      :http-request="uploadFile">
      <el-button slot="trigger" size="small" type="primary">選取文件</el-button>
      <el-button style="margin-left: 10px;" size="small" type="success" @click="submitUpload">上傳到服務器</el-button>
      <div slot="tip" class="el-upload__tip">只能上傳mp3文件,且單次不超過500M</div>
    </el-upload>
</div>

export default {
    name: 'uploadMusic',
    data() {
      return {
        fileType:'video',
        fileData: new FormData(),
        headers:{},
      }
    },
    created() {
     this.headers={} //此處須要與server約定具體的header
    },
    methods:{
      //覆蓋默認的上傳行爲,能夠自定義上傳的實現
      uploadFile(file){
        this.fileData.append('files',file.file);  //服務器最終接收到的是files[]數組
      },
      submitUpload() {
        this.$refs.upload.submit();//手動上傳文件,此處表單提交後會自動調用uploadFile()方法,若是是多個文件就調用屢次
        this.fileData.append('file_type',this.fileType);
        //傳給server的文件數據,server可自行解析文件相關屬性
        this.$http.post('xxxxxxxxxx',this.fileData,{headers:this.headers}).then(response=>{
          let resp=response.data
          if (resp.status == 'ok') {
            this.$message({
              message: '上傳成功',
              type: 'success'
            })
          } else {
            this.$message({
              message: '上傳失敗,請重試',
              type: 'error'
            })
          }
        })
      },
    }
}
相關文章
相關標籤/搜索