ZBLOG

以下是你提供的代码片段的改进版本,并添加了导入文件部分与接口联调的实现。这段代码展示了一个用于上传 Excel 文件的模态框,用户可以选择文件并在点击“导入”按钮后上传。

  1. <template>
  2. <a-modal v-model:open="open" title="上传文件" @ok="handleOk">
  3. <div style="padding: 10px 0px">
  4. <span>上传文件:</span>
  5. <a-upload
  6. :before-upload="beforeUpload"
  7. @change="handleChange"
  8. accept=".xlsx,.xls"
  9. show-upload-list="{ showRemoveIcon: true }"
  10. :file-list="fileList"
  11. :on-remove="handleRemove"
  12. >
  13. <a-button>导入文件</a-button>
  14. </a-upload>
  15. </div>
  16. </a-modal>
  17. </template>
  18. <script setup lang="ts">
  19. import { ref } from 'vue';
  20. import { request } from 'your-request-library'; // 替换为你的请求库
  21. const open = ref(false);
  22. const fileList = ref([]);
  23. const beforeUpload = (file) => {
  24. const isExcel = file.type === 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' ||
  25. file.type === 'application/vnd.ms-excel';
  26. if (!isExcel) {
  27. // 可以在这里提示用户只允许上传 Excel 文件
  28. alert('只能上传 Excel 文件!');
  29. }
  30. return isExcel;
  31. };
  32. const handleChange = ({ fileList: newFileList }) => {
  33. fileList.value = newFileList;
  34. };
  35. const handleRemove = (file) => {
  36. const index = fileList.value.indexOf(file);
  37. if (index >= 0) {
  38. fileList.value.splice(index, 1);
  39. }
  40. };
  41. const updataData = async () => {
  42. const formData = new FormData();
  43. if (fileList.value.length > 0) {
  44. formData.append('file', fileList.value[0].originFileObj); // 获取第一个文件
  45. try {
  46. const response = await request({
  47. url: '/api/upload', // 替换为实际的接口地址
  48. method: 'POST',
  49. data: formData,
  50. });
  51. console.log('上传成功:', response);
  52. open.value = false; // 上传成功后关闭模态框
  53. } catch (error) {
  54. console.error('上传失败:', error);
  55. }
  56. // 清空已上传列表(可选)
  57. fileList.value = [];
  58. } else {
  59. alert('请先选择文件');
  60. }
  61. };
  62. const handleOk = () => {
  63. updataData();
  64. };
  65. </script>
  66. <style scoped>
  67. /* 添加样式(如需要) */
  68. </style>

注意事项:

  1. request:确保你根据自己的项目替换 request 方法。
  2. 处理文件:此示例中使用的是 FormData 对象来将文件作为 POST 请求发送到服务器。
  3. 错误处理和反馈:建议添加更完善的用户反馈机制,比如显示成功或失败消息。
  4. 接受多个文件:如果需要支持多个文件,可以调整 file-list 和相关逻辑。

希望这能满足你的需求!如有任何问题,请随时问我。


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

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

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

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

联系我们

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

微信号:3007537140

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

关注我们
x

注册

已经有帐号?