Skip to content

Instantly share code, notes, and snippets.

@p1mo
Created December 14, 2023 23:33
Show Gist options
  • Save p1mo/26c70679123a22fee38b59eba2c5c8c4 to your computer and use it in GitHub Desktop.
Save p1mo/26c70679123a22fee38b59eba2c5c8c4 to your computer and use it in GitHub Desktop.
tauri v1 - custom protocol - example (read image)

very simple & ugly example for tauri's custom protocol

This example uses mdata as custom protocol and csp img-src

tauri.conf.json

{
    "tauri" : {
        "allowlist" : {
            "protocol": {
                "all": true,
                "asset": true,
                "assetScope": [ "$HOME/**" ]
            }
        },
        "security": {
            "csp": "img-src 'self' mdata: https://mdata.localhost/;"
        }
    }
}

main.rs

get_file_path is an custom function

use tauri::http::status::StatusCode;

fn main (){
    tauri::Builder::default()
    .register_uri_scheme_protocol("mdata", |_app, req| {

        // custom function
        let file_path = get_file_path("mdata", req.uri());

        // check if file exists and read file
        let (code, content) = if file_path.exists() {
            (StatusCode::OK, std::fs::read(&file_path).unwrap())
        } else {
            (StatusCode::NOT_FOUND, Vec::new())
        };
        
        // register type
        let (status, data, mime) = match file_path.extension().unwrap().to_str() {
            Some("jpg") => (code, content, "image/jpeg"),
            _ => (StatusCode::NOT_IMPLEMENTED, content, "text/plain")
        };

        tauri::http::ResponseBuilder::new()
        .status(status)
        .mimetype(mime)
        .body(data)

    })
    .run(tauri::generate_context!())
    .expect("error while running tauri application");
}

// ugly custom function
fn get_file_path(uri_scheme : &str, req_uri : &str) -> PathBuf {
    let formated = format!("{}://localhost/", uri_scheme);
    let uri = req_uri.replace(&formated, "");
    let req_path = percent_encoding::percent_decode_str(&uri).decode_utf8_lossy().to_string();
    let home_dir = tauri::api::path::home_dir().unwrap();
    std::path::Path::new(&home_dir.as_path()).join(&req_path)
}

main.js

import { convertFileSrc} from "@tauri-apps/api/tauri";

const file_path = await convertFileSrc("test/example.jpg", "mdata"); 
const addimage = document.getElementById("addimage");

if(addimage) {
    addimage.innerHTML = `<img src="${file_path}" alt="image" width="32px" />`;
}

The example.jpg should be here

  • windows C:/Users/username/test/example.jpg
  • linux /home/username/test/example.jpg
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment