欢迎来到尧图网

客户服务 关于我们

您的位置:首页 > 教育 > 幼教 > element plus上传文件 点击确认后文件上传到接口

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

2024/10/25 6:22:48 来源:https://blog.csdn.net/weixin_42220130/article/details/142531664  浏览:    关键词:element plus上传文件 点击确认后文件上传到接口

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

安装 Element Plus

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

npm install element-plus

组件代码示例

<template><div><el-uploadclass="upload-demo"dragaction="":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 文件的功能,可以根据需要进行进一步的调整与扩展。

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com