前端获取文件夹内文件

· 通过 input file 实现获取文件夹里的所有文件

html 复制代码
<el-button type="primary" @click="openFileInput">选取文件夹</el-button>
<input type="file" ref="dirInput" webkitdirectory directory style="display: none;" @change="changeFileInput">
javascript 复制代码
openFileInput(type){ this.$refs.dirInput.click(); }
changeFileInput(e){
  if(e.target.files.length === 0) {
      this.$message.error('未选择任何文件或文件夹!');
      return;
  }
  let fileList = []
  Array.from(e.target.files).forEach(file => {
      const fileNameParts = file.name.split('.');
      if(fileNameParts[1]!=='json') return;
      const name = fileNameParts[0]
      fileList.push({
          name: name,
          path: file.webkitRelativePath,
      })
  })
}

· 获取文件具体内容

javascript 复制代码
/**
 * 获取本地文件内容
 * @param {string} filePath - 本地文件的路径(相对路径或绝对路径)
 * @returns {Promise<string>} 返回文件内容的 Promise
 */
async getLocalFile(filePath) {
    try {
        const response = await fetch(filePath);

        // 如果请求失败(例如文件不存在返回 404),抛出错误
        if (!response.ok) {
        throw new Error(`请求失败: ${response.status} ${response.statusText}`);
        }

        // 将响应体解析为文本并返回
        return await response.text();
    } catch (error) {
        console.error('获取文件时发生错误:', error.message);
        throw error; // 继续向上抛出错误,便于调用者处理
    }
}