ZBLOG

导入 上传文件:

在你的代码基础上,我将帮助你实现上传文件的功能。具体来说,你需要处理文件的选择、上传逻辑和文件的实际传输到服务器。以下是修改后的代码:

修改后的代码

  1. <template>
  2. <div class="form-tool">
  3. <a-button class="margin-right-10 button-light-blue" @click="openModal">导入</a-button>
  4. <a-modal v-model:open="open" title="上传文件" @ok="handleOk">
  5. <div style="padding: 10px 0px">
  6. <span>上传文件:</span>
  7. <a-upload
  8. :before-upload="beforeUpload"
  9. :on-change="handleChange"
  10. accept=".xlsx,.xls"
  11. :show-upload-list="{ showRemoveIcon: true }"
  12. :file-list="fileList"
  13. ref="uploadRef"
  14. >
  15. <a-button>导入文件</a-button>
  16. </a-upload>
  17. </div>
  18. </a-modal>
  19. </div>
  20. </template>
  21. <script setup>
  22. import { ref } from 'vue';
  23. import { importCasePool } from '../../utils'; // 确保此路径正确
  24. const open = ref(false);
  25. const fileList = ref([]); // 存储上传的文件列表
  26. const uploadRef = ref(null); // 用于访问 a-upload 实例
  27. const openModal = () => {
  28. open.value = true; // 打开模态框
  29. };
  30. const beforeUpload = (file) => {
  31. const isExcelFile = /\.(xlsx|xls)$/.test(file.name); // 检查是否为 Excel 文件
  32. if (!isExcelFile) {
  33. message.error('您只能上传 Excel 文件!');
  34. }
  35. return isExcelFile; // 返回 true 或 false 控制是否允许上传
  36. };
  37. const handleChange = (info) => {
  38. fileList.value = info.fileList; // 更新文件列表
  39. if (info.file.status === 'done') {
  40. message.success(`${info.file.name} 文件上传成功`);
  41. } else if (info.file.status === 'error') {
  42. message.error(`${info.file.name} 文件上传失败`);
  43. }
  44. };
  45. const handleOk = async () => {
  46. const formData = new FormData();
  47. fileList.value.forEach((file) => {
  48. formData.append('files[]', file.originFileObj); // 将每个选中的文件添加到 FormData 中
  49. });
  50. try {
  51. const response = await importCasePool(formData); // 调用导入接口,传递 FormData
  52. console.log(response);
  53. message.success('文件导入成功');
  54. open.value = false; // 成功后关闭模态框
  55. fileList.value = []; // 清空文件列表,以便下次使用
  56. uploadRef.value.clear(); // 清空 a-upload 的内容,如果支持这个方法的话
  57. } catch (error) {
  58. console.error(error);
  59. message.error('文件导入失败');
  60. }
  61. };
  62. </script>
  63. <style scoped>
  64. /* 自定义样式 */
  65. </style>

功能说明:

  1. fileList: 我们创建了一个响应式 ref 用于存储当前选择的文件列表。
  2. beforeUpload: 在这个函数中,我们对上传的文件进行类型检查,确保用户只能选择 .xlsx.xls 格式的 Excel 文件。
  3. handleChange: 此函数会更新 fileList,并根据不同状态给出相应提示信息。
  4. handleOk:
    • 创建一个 FormData 对象,将所有选中的文件添加到其中。
    • 使用 importCasePool(formData) 方法来将数据发送到服务器,并处理成功或失败的回调。

注意事项:

  • 确保 importCasePool() 函数能够接受 FormData 参数,并正确处理它(通常这是一个 POST 请求)。
  • 可以通过 Ant Design Vue 提供的 message 模块来显示操作反馈,确保在页面中引入相应模块。

如果有其他问题或者需要进一步调整,请告诉我!


内容由零声教学AI助手提供,问题来源于学员提问

本站部分文章来源于网络,版权归原作者所有,如有侵权请联系站长删除。
转载请注明出处:https://golang.0voice.com/?id=21017

分享:
扫描分享到社交APP
上一篇
下一篇
发表列表
游客 游客
此处应有掌声~
评论列表

还没有评论,快来说点什么吧~

联系我们

在线咨询: 点击这里给我发消息

微信号:3007537140

上班时间: 10:30-22:30

关注我们
x

注册

已经有帐号?