You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Tauri+TypeScript中如何基于用户选择的目录创建文件夹?

解决方案:Tauri中用户自选目录下创建子目录

核心结论

不能将用户自选的任意路径转换为BaseDirectory枚举值,因为BaseDirectory是Tauri预定义的系统特定固定目录(如应用本地数据目录、系统文档目录等),仅用于指代这些预设路径,无法表示用户选择的自定义路径。

正确实现方式

当用户通过dialog.open选中目标目录后,直接使用该完整路径来创建子目录即可,无需使用FsDirOptions的dir参数(该参数仅配合相对路径使用)。

修正后的代码示例

import { open } from '@tauri-apps/api/dialog';
import { join } from '@tauri-apps/api/path';
import { createDir } from '@tauri-apps/api/fs';

// 使用async/await简化异步逻辑
async function createSubdirInUserSelectedFolder() {
  try {
    // 1. 让用户选择目标父目录
    const parentDir = await open({
      directory: true,
      multiple: false
    });

    if (!parentDir) return; // 用户取消选择

    // 2. 定义要创建的子目录名称
    const subdirName = "my_export_folder";
    // 拼接完整的子目录路径
    const fullSubdirPath = await join(parentDir, subdirName);

    // 3. 创建子目录(直接传入完整路径,无需指定dir参数)
    await createDir(fullSubdirPath, { recursive: true });
    console.log("子目录创建成功");
  } catch (error) {
    console.error("创建目录失败:", error);
  }
}

// 调用函数
createSubdirInUserSelectedFolder();

权限配置说明

确保tauri.conf.json中开启必要的权限:

{
  "tauri": {
    "allowlist": {
      "dialog": {
        "open": true
      },
      "fs": {
        "createDir": true,
        "scope": ["*"] // 允许访问所有路径(若需更严格可缩小范围,但用户自选路径需被包含)
      }
    }
  }
}

注:用户通过dialog.open选中的路径,Tauri会自动授予临时文件系统访问权限,无需额外配置特定路径到scope中(但scope需允许足够的范围)。

内容的提问来源于stack exchange,提问作者eddieconnecti

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.14 13:15:20