tauri2项目打开某个文件夹,类似于mac系统中的 open ./

在 Tauri 2 项目中打开文件夹

在 Tauri 2 项目中,你可以使用以下几种方法来打开文件夹,类似于 macOS 中的 open ./ 命令功能:

方法一:使用 shell 命令

rust 复制代码
use tauri::Manager;

#[tauri::command]
async fn open_folder(path: String) -> Result<(), String> {
    #[cfg(target_os = "macos")]
    let command = "open";
    
    #[cfg(target_os = "windows")]
    let command = "explorer";
    
    #[cfg(target_os = "linux")]
    let command = "xdg-open";
    
    std::process::Command::new(command)
        .arg(&path)
        .spawn()
        .map_err(|e| e.to_string())?;
    
    Ok(())
}

fn main() {
    tauri::Builder::default()
        .invoke_handler(tauri::generate_handler![open_folder])
        .run(tauri::generate_context!())
        .expect("error while running tauri application");
}

然后在你的前端代码中调用:

rust 复制代码
import { invoke } from '@tauri-apps/api/tauri';

// 打开当前目录
invoke('open_folder', { path: '.' });

方法二:使用 Tauri 的 dialog API

Tauri 2 提供了更安全的 API 来打开文件夹:

rust 复制代码
use tauri::Manager;

#[tauri::command]
async fn open_folder(app: tauri::AppHandle, path: String) -> Result<(), String> {
    app.shell()
        .open(&path, None)
        .map_err(|e| e.to_string())?;
    Ok(())
}

方法三:使用平台特定的 API

对于更精细的控制,你可以使用平台特定的 API:

rust 复制代码
#[tauri::command]
async fn open_folder(path: String) -> Result<(), String> {
    if cfg!(target_os = "macos") {
        std::process::Command::new("open")
            .arg(&path)
            .spawn()
            .map_err(|e| e.to_string())?;
    } else if cfg!(target_os = "windows") {
        std::process::Command::new("explorer")
            .arg(&path)
            .spawn()
            .map_err(|e| e.to_string())?;
    } else {
        std::process::Command::new("xdg-open")
            .arg(&path)
            .spawn()
            .map_err(|e| e.to_string())?;
    }
    Ok(())
}

注意事项

  1. 确保在 tauri.conf.json 中允许 shell 命令执行(如果使用方法一或三)
  2. 对于生产环境,建议使用方法二(dialog API)以获得更好的安全性和跨平台兼容性
  3. 路径处理时要注意跨平台兼容性,可以使用 std::path::Path 来处理路径

选择哪种方法取决于你的具体需求和安全性考虑。方法二(使用 Tauri 的 dialog API)通常是推荐的方式,因为它经过了 Tauri 团队的优化和测试。

相关推荐
ricky_fan5 小时前
(OpenAI)Codex 安装、部署使用方式
python·macos·conda·vim
音源部落8 小时前
Cubase15 R2R/VR一键安装完整版本下载安装Nuendo 14最新版本下载安装支持Win/Mac 双系统版本加104G原厂音源Mac系统不关SIP安装编曲软件Cubase 15.0.10下载
macos·vr·cubase·cubase15·nuendo·nuendo14
代码AI弗森14 小时前
Mac 长时间处在高温运行会怎么样?
macos
心愿许得无限大14 小时前
macOS下打开麦克风崩溃
macos
汤姆yu1 天前
Mac 上 2026 版 OpenClaw 安装与配置全流程
macos·openclasw安装
MonkeyKing_sunyuhua1 天前
K8S执行MAC打出的本地镜像错误:exec /usr/local/bin/uvicorn: exec format error
macos·容器·kubernetes
小路恢弘1 天前
xcode替换LLVM插件
ide·macos·xcode
ChengQianO1 天前
从 0 开始:Mac 下 UTM 虚拟机安装 ROS Noetic(Ubuntu 20.04)
linux·ubuntu·macos
草帽lufei1 天前
macOS中的Cursor等软件突然不能用了
macos·cursor
Rabbit_QL2 天前
【Warp+Claude】任务完成自动通知(macOS + Warp 版)
macos·策略模式