在Vue3中获取文件夹绝对路径

<template>

  <el-button type="primary" @click="promptFolderSelection">选择文件夹</el-button>

  <input type="file" ref="folderInput" id="fileImage" name="fileImage" webkitdirectory style="display: none"

    @change="handleFolderSelect" />

  <div v-if="selectedFolderPath">

    <h3>选择的文件夹路径:</h3>

    <p>{{ selectedFolderPath }}</p>

  </div>

</template>

<script setup>

import { ref, onMounted } from 'vue';

import { ElButton } from 'element-plus';

const files = ref([]);

const selectedFolderPath = ref('');

const folderInput = ref(null);

onMounted(() => {

  if (!folderInput.value) {

    console.error('folderInput 未正确引用');

  }

});

const promptFolderSelection = () => {

  if (folderInput.value) {

    folderInput.value.click();

  } else {

    console.error('folderInput 未正确引用');

  }

};

const handleFolderSelect = event => {

  const selectedFiles = Array.from(event.target.files);

  const rootPath = getRootPath(selectedFiles);

  selectedFolderPath.value = rootPath;

  console.log("选择的文件夹路径:", selectedFolderPath.value);

};

const getRootPath = (files) => {

  if (files.length === 0) {

    return '';

  }

  // 获取第一个文件的相对路径

  const firstFileRelativePath = files[0].webkitRelativePath;

  // 去掉文件名部分,只保留文件夹路径

  const relativeFolderPath = firstFileRelativePath.substring(0, firstFileRelativePath.lastIndexOf('/'));

  // 获取第一个文件的绝对路径

  const firstFile = document.getElementById('fileImage').files[0];

  const absoluteFilePath = firstFile.path;

  // 去掉文件名部分,只保留文件夹路径

  const absoluteFolderPath = absoluteFilePath.substring(0, absoluteFilePath.lastIndexOf('\\'));

  // 计算最终的文件夹路径

  const folderPath = absoluteFolderPath + '\\' + relativeFolderPath;

  return folderPath;

};

</script>

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值