vue+elementUI使用upload组件实现文件上传功能

项目中需要上传文件,用的vue+elementUI,使用的上传组件是elementUI的el-upload组件,通常用到过的上传方式有两种

1.上传到云服务器,再把返回的连接给后端

2.以formdata的方式直接传给后端

这里使用的是第二种方式手动上传的方式进行上传文件,较为简单。

过多的文字描述让人头大,直接上代码。

<template>
  <div class="contain">
    //accept为上传的格式
    //limit为上传文件限制数
    //file-list为上传文件列表
    <el-upload
      class="upload-demo sendData"
      :action="UploadUrl()"
      accept=".xls"
      :on-preview="handlePreview"
      :on-change="fileChange"
      :before-remove="beforeRemove"
      :limit="1"
      :http-request="uploadFile"
      :auto-upload="true"
      :on-exceed="handleExceed"
      :file-list="fileList"
    >
      <el-button size="small" type="primary" class="dataSendBtn">上传数据</el-button>
      <!-- <div slot="tip" class="el-upload__tip">只能上传jpg/png文件,且不超过500kb</div> -->
    </el-upload>
  </div>
</template>
<script>
export default {
  data() {
    return {
      fileList: [],
    };
  },
  created() {
    this.readExcel();
  },
  methods: {
    UploadUrl() {
      // 因为action参数是必填项,我们使用二次确认进行文件上传时,直接填上传文件的url会因为没有参数导致api报404,所以这里将action设置为一个返回为空的方法就行,避免抛错
      return '';
    },
    fileChange(file, fileList) {
      this.fileList.push(file.raw);
      console.log(this.fileList);
    },
    handleCurrentChange() {},
    handleSizeChange() {},
    sendData() {
      console.log('sadsad');
    },
  
    uploadFile(val) {
      if (this.fileList.length === 0) {
        this.$message.warning('请上传文件');
      } else {
        const form = new FormData();
        // file和flag分别为后端要求上传的参数名,类似于post、get等请求中的参数
        form.append('file', val.file);
        form.append('flag', true);
        this.fileList = [];
        this.$api
          .post('/import/upload', form)
          .then((res) => {
            console.log(res);
            if (res) {
              console.log(res);
              this.$message({
                message: '上传成功',
                type: 'success',
              });
            } else {
              console.log(res);
            }
          })
          .catch((res) => {
            console.log(res);
          });
      }
    },
    handlePreview(file) {
      console.log(file);
    },
    // 文件限制钩子函数
    handleExceed(files, fileList) {
      this.$message.warning(`当前限制选择 1 个文件,本次选择了 ${files.length} 个文件,共选择了 ${files.length + fileList.length} 个文件,请刷新页面后重试。`);
    },
    beforeRemove(file, fileList) {
      return this.$confirm(`确定移除 ${file.name}?`);
    },
  },
};
</script>

<style lang="scss" scoped>
::v-deep .el-dialog__headerbtn {
  display: none;
}
.sendData {
  position: absolute;
  right: 0px;
  top: -40px;
  width: 120px;
  height: 30px;
}
.dataSendBtn {
  width: 120px;
}
.contain {
  position: relative;
}
</style>

  • 4
    点赞
  • 29
    收藏
    觉得还不错? 一键收藏
  • 5
    评论
评论 5
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值