自定義Element的Upload 上傳事件,不使用action屬性上傳

自定義Element的Upload 上傳事件,不使用action屬性上傳

<template>
 <div class="upload-container">
         <el-upload
          class="upload-demo"
          action=""
          :on-preview="handlePreview"
          :on-remove="handleRemove"
          :file-list="fileList"
          :before-upload="BeforeUpload"
          :http-request="Upload"
          list-type="picture">
          <el-button size="small" type="primary">點擊上傳</el-button>
          <div slot="tip" class="el-upload__tip">只能上傳jpg/png文件,且不超過500kb</div>
        </el-upload>
 </div>
</template>
<script>
import axios from 'axios';
import qs from 'qs';
  export default {
    data(){
      return {
          fileList: [{name: 'food1.jpeg', url: 'https://fuss10.elemecdn.com/3/63/4e7f3a15429bfda99bce42a18cdd1jpeg.jpeg?imageMogr2/thumbnail/360x360/format/webp/quality/100'}],
          newFile:new FormData() //   1. 定義一個newFile變量(FormData 對象) 
      }
    },
    methods: {
      handleRemove(file, fileList) {
        console.log(file, fileList);
      },
      handlePreview(file) {
        console.log(file);
      },
      BeforeUpload(file){
       if(file){
          this.newFile.append('file',file); //  2. 上傳之前,拿到file對象,並將它添加到剛剛定義的FormData對象中。 
           console.log(this.newFile.get('file'))
       }else{
         return false;
       }     
      },
      Upload(){
        const newData= this.newFile; //  3. 拿到剛剛的數據,並將其傳給後臺
        axios({
          url:'https://jsonplaceholder.typicode.com/posts/',
          method:'post',
          data: newData,
          headers:{
          'Content-Type':'multipart/form-data'
          }
        })
        .then(res => {
          console.log('res:',res)
        }).catch(err => {
          console.log(err)
        })
      }
    }
  }
</script>
<style lang="scss">
  .upload-container{
    width: 250px;
    padding:150px;
  }
</style>

以下分別爲:圖片上傳成功效果、傳給後臺的數據格式以及後臺的響應數據截圖。
在這裏插入圖片描述在這裏插入圖片描述在這裏插入圖片描述
更多詳細用法,參考官網

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章