rusttaurileptos

How to return data after using pick_file from within a tauri command?


I am trying to pick a file via a tauri command, convert it to base64, and to send it to my leptos view. I cannot figure out how to wait for file pick to happen. With the code below the command returns immediately without waiting for the pick_file to exit.

//A simplified version of what I am trying to achive
#[tauri::command]
pub fn select_image<R: Runtime>(app_handle: tauri::AppHandle<R>) -> Option<String> {
    let mut file_base64: Option<String> = None;
    app_handle.dialog().file().pick_file(move |file_path| {
        //convert file_path to base64
    });
    //How to wait here for file pick to happen?
    return file_base64;
}

I understand that all I am doing here is giving pick_file a closure and returning None. But how do I wait for pick_file to exit within the command. Maybe my approach to the problem is wrong? Please advice on how I can achieve this?

Update

If you are also looking for something like this, instead of passing base64 like I did, instead looking into asset protocol. this way you will be able to access your assets from appdata via "http://asset.localhost/<full path to your asset>". Look into asset protocol configuration.


Solution

  • how do I wait for pick_file to exit within the command.

    Use blocking_pick_file instead:

    //A simplified version of what I am trying to achive
    #[tauri::command]
    pub fn select_image<R: Runtime>(app_handle: tauri::AppHandle<R>) -> Option<String> {
        let file_path = app_handle.dialog().file().blocking_pick_file();
        let mut file_base64: Option<String>;
        //convert file_path to base64
        return file_base64;
    }