element plus上传文件 点击确认后文件上传到接口

下面是一个使用 Element Plus 的示例代码,展示了如何实现上传 .xlsx.xls 文件的功能,并在上传后打印文件名和上传状态,同时通过接口将文件以流的形式上传。

安装 Element Plus

首先,确保你已经安装了 Element Plus。可以使用以下命令安装:

npm install element-plus

组件代码示例

<template>
  <div>
    <el-upload
      class="upload-demo"
      drag
      action=""
      :on-change="handleChange"
      :before-upload="beforeUpload"
      multiple
      :file-list="fileList"
      :show-file-list="false"
    >
      <i class="el-icon-upload"></i>
      <div class="el-upload__text">将文件拖到此处,或<em>点击上传</em></div>
      <div class="el-upload__tip" slot="tip">只支持.xlsx和.xls文件</div>
    </el-upload>

    <el-button type="primary" @click="submitFiles">确认上传</el-button>

    <div v-if="uploadStatus">
      <p>文件名: {{ uploadedFileName }}</p>
      <p>上传状态: {{ uploadStatus }}</p>
    </div>
  </div>
</template>

<script>
import { ref } from 'vue'
import axios from 'axios'

export default {
  setup() {
    const fileList = ref([])
    const uploadedFileName = ref('')
    const uploadStatus = ref('')

    const handleChange = (file, fileList) => {
      if (file.status === 'ready') {
        uploadedFileName.value = file.name
      }
    }

    const beforeUpload = (file) => {
      const isExcel =
        file.type === 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' ||
        file.type === 'application/vnd.ms-excel'
      if (!isExcel) {
        this.$message.error('上传文件只能是 .xlsx 或 .xls 格式!')
      }
      return isExcel
    }

    const submitFiles = async () => {
      if (fileList.value.length === 0) {
        this.$message.warning('请先选择文件!')
        return
      }

      const formData = new FormData()
      fileList.value.forEach(file => {
        formData.append('files', file.raw) // 将文件添加到 FormData
      })

      try {
        const response = await axios.post('YOUR_API_ENDPOINT', formData, {
          headers: {
            'Content-Type': 'multipart/form-data',
          },
        })
        uploadStatus.value = response.data.success ? '上传成功' : '上传失败'
      } catch (error) {
        uploadStatus.value = '上传发生错误'
        console.error(error)
      }
    }

    return {
      fileList,
      uploadedFileName,
      uploadStatus,
      handleChange,
      beforeUpload,
      submitFiles,
    }
  },
}
</script>

<style>
.upload-demo {
  margin: 20px 0;
}
</style>

功能说明

  1. 文件上传:使用 el-upload 组件实现文件的拖拽和点击上传功能。
  2. 文件类型检查:在 before-upload 钩子中,验证上传文件是否为 .xlsx.xls 格式。
  3. 文件状态管理:在 handleChange 方法中,记录上传的文件名。
  4. 提交文件:通过 Axios 将选中的文件以二进制流的方式上传到指定的 API 接口。
  5. 上传反馈:根据响应结果显示上传状态。

注意事项

  • 请将 'YOUR_API_ENDPOINT' 替换为你的实际 API 地址。
  • 确保后端能够处理 multipart/form-data 类型的请求并正确解析文件流。

这样,你就拥有了一个完整的上传 Excel 文件的功能,可以根据需要进行进一步的调整与扩展。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值