半原生的上傳文件小demo

<template>
  <div class="exportFile">
    <div>
      <h4>選擇導入文件</h4>
      <span>(請選擇excel文件導入)</span>
      <div class="chooseFile">
        <label>文件:</label>
        <input type="file" id="upfile" name="upfile" />
      </div>
      <a @click="exportTemplet">下載模板</a>
      <div>
        <button class="confirmBtn" type="button" @click="confirmExport">確定</button>
        <button class="cancelBtn" type="button" @click="cancelExport">取消</button>
      </div>
    </div>
  </div>
</template>

<script>
  export default {
    name: "time-demo",
    data() {
      return {
        files: ''
      }
    },
    methods: {
      // 模板下載
      exportTemplet() {

      },
      // 確定
      confirmExport() {
        let files = document.getElementById("upfile").files;
        // console.log(files)
        if (files.length === 0) {
          this.$alert("未選擇導入文件", "提示", {
            confirmButtonText: '確定',
            center: true,
            type: 'warnimg'
          })
        } else {
          let formData = new FormData();
          formData.append("upfile",files[0])
          this.export(formData);
        }
      },
      // 取消
      cancelExport() {

      },
      // 上傳
      export(files) {
        const loading = this.$loading({
          lock: true,
          text: "正在導入...",
          spinner: 'el-icon-loading',
          background: 'rgba(0, 0, 0, 0.7)'
        });
        axios({
          data: files,
          methods: "post",
          headers: {"Content-Type": "multipart/form-data"},
          url: '後端接口地址'
        }).then(res => {
          if(res.data.returnCode === 0) { // 接口請求成功
            loading.close();
            // 執行相關成功後的相關操作
          }
        }).catch(err => {
          loading.close();
          // 執行錯誤的相關操作
        })
      }
    }
  }
</script>

<style scoped>
  .exportFile {
    position: fixed;
    width: 100%;
    height: 100%;
    top: 0px;
    left: 0px;
    z-index: 10;
    background: rgba(0,0,0,0.5);
  }
  .exportFile>div {
    position: fixed;
    text-align: center;
    width: 350px;
    height: 300px;
    top: 50%;
    left: 50%;
    z-index: 99;
    transform: translate(-200px,-125px);
    background: #fff;
  }
  .exportFile>div h4 {
    font-size: 20px;
    color: #1c1d14;
    height: 40px;
    line-height: 40px;
    padding-top: 10px;
    box-sizing: border-box;
  }
  .exportFile label {
    font-size: 14px;
    font-weight: normal;
    display: inline-block;
    text-align: right;
  }
  .exportFile>div .chooseFile {
    margin-top: 20px;
    margin-bottom: 20px;
  }
  .exportFile>div a {
    display: inline-block;
    width: 100%;
    text-align: left;
    padding-left: 15px;
    text-decoration: underline;
    color: #5C8FFE;
    margin-bottom: 10px;
  }
</style>

 

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