<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>