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

Rust Yew WASM应用中读取Book.txt文件的可行方案求助

解决方案

核心原因

Wasm运行在浏览器沙箱中,没有直接访问本地文件系统的权限,std::fs是针对原生平台的API,在浏览器环境下必然失效,更换编译目标也无法解决这个问题。

具体实现方案

方案一:通过HTTP请求读取静态文件

这是浏览器环境下获取静态资源的标准方式,符合GitHub Pages的部署需求。

1. 添加依赖

在Cargo.toml中引入兼容Wasm的HTTP请求库:

[dependencies]
yew = "0.20"
reqwest = { version = "0.11", features = ["wasm-bindgen"] }
wasm-bindgen-futures = "0.4"

2. 组件内实现读取逻辑

use yew::prelude::*;
use wasm_bindgen_futures::spawn_local;
use reqwest::Client;

#[function_component(App)]
fn app() -> Html {
    let book_content = use_state(|| String::from("加载中..."));

    {
        let book_content = book_content.clone();
        use_effect_with_deps(move |_| {
            spawn_local(async move {
                let client = Client::new();
                match client.get("/Book.txt").send().await {
                    Ok(resp) => {
                        if resp.status().is_success() {
                            match resp.text().await {
                                Ok(content) => book_content.set(content),
                                Err(e) => book_content.set(format!("读取内容失败: {}", e)),
                            }
                        } else {
                            book_content.set(format!("请求失败: {}", resp.status()));
                        }
                    }
                    Err(e) => book_content.set(format!("发送请求失败: {}", e)),
                }
            });
            || ()
        }, ());
    }

    html! {
        <div>
            <h1>{"书籍内容"}</h1>
            <pre>{(*book_content).clone()}</pre>
        </div>
    }
}

fn main() {
    yew::Renderer::<App>::new().render();
}

3. 验证Trunk配置

确保Trunk.toml中正确配置了文件复制(如果手动配置的话):

[[copy]]
from = "Book.txt"
to = "Book.txt"

运行trunk serve后,访问http://localhost:8080/Book.txt能看到文件内容即为配置正确。

4. GitHub Pages部署注意事项

  • Trunk编译后会生成dist目录,直接将该目录的内容推送到GitHub Pages即可。
  • 如果仓库路径带二级目录(如username/book-app),需要调整请求路径为/book-app/Book.txt,可以通过web_sys::window().unwrap().location().pathname()动态获取基础路径拼接URL。

方案二:将文件嵌入Wasm二进制

适合小型文件,无需额外HTTP请求,直接将文件打包进Wasm。

1. 添加依赖

[dependencies]
yew = "0.20"
rust-embed = "6.4"

2. 嵌入并读取文件

use yew::prelude::*;
use rust_embed::RustEmbed;

#[derive(RustEmbed)]
#[folder = "."] // 指定Book.txt所在的目录
struct Assets;

#[function_component(App)]
fn app() -> Html {
    let book_content = match Assets::get("Book.txt") {
        Some(file) => String::from_utf8_lossy(&file.data).to_string(),
        None => "未找到Book.txt文件".to_string(),
    };

    html! {
        <div>
            <h1>{"书籍内容"}</h1>
            <pre>{book_content}</pre>
        </div>
    }
}

fn main() {
    yew::Renderer::<App>::new().render();
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.08 08:50:22