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

使用Tauri+React(TypeScript)加载本地图片遇404问题求助

问题:Tauri + React(TypeScript) 加载本地目录图片出现404错误

使用Tauri和React(TypeScript)开发应用时,尝试将默认图标替换为$HOME/.config/miguel-file-manager/file_explorer_icons/icons8-file-48.png路径下的自定义图标,开发者工具提示Failed to load resource: the server responded with a status of 404 (Not Found)。相关代码如下:

export type ItemType = "File" | "Folder"

interface ItemProps {
  itemType: ItemType,
  itemName: string | undefined
}

function Item(props: ItemProps) {

  return (
    <div>
      <img src={"$HOME/.config/miguel-file-manager/file_explorer_icons/icons8-file-48.png"}/>
      {props.itemName}
    </div>
  )
}

export default Item
解决方案

1. 问题根源

  • React运行在Tauri的WebView环境中,无法直接识别$HOME这类系统环境变量。
  • Tauri默认限制文件系统访问权限,未授权的路径会被拦截。
  • 直接使用本地绝对路径不符合WebView的资源加载规则。

2. 具体解决步骤

步骤1:配置Tauri文件访问权限

在项目根目录的tauri.conf.json中,修改allowlist.fs配置,添加目标目录的访问权限:

{
  "tauri": {
    "allowlist": {
      "fs": {
        "readFile": true,
        "scope": ["$HOME/.config/miguel-file-manager/**"]
      }
    }
  }
}

步骤2:用Tauri API获取正确路径并加载图片

通过Tauri的@tauri-apps/api提供的路径工具和文件读取API,正确获取本地图片并转为WebView可识别的格式:

首先确保安装API包:

npm install @tauri-apps/api

修改Item组件:

import { useState, useEffect } from 'react';
import { readBinaryFile } from '@tauri-apps/api/fs';
import { resolve, appConfigDir } from '@tauri-apps/api/path';

export type ItemType = "File" | "Folder"

interface ItemProps {
  itemType: ItemType,
  itemName: string | undefined
}

function Item(props: ItemProps) {
  const [imageSrc, setImageSrc] = useState<string>('');

  useEffect(() => {
    const loadIcon = async () => {
      // 获取应用配置目录路径
      const configDir = await appConfigDir();
      // 拼接图标完整路径
      const iconPath = await resolve(configDir, 'file_explorer_icons', 'icons8-file-48.png');
      // 读取图片二进制数据并转为base64
      const imageBuffer = await readBinaryFile(iconPath);
      const base64 = btoa(String.fromCharCode(...new Uint8Array(imageBuffer)));
      setImageSrc(`data:image/png;base64,${base64}`);
    };

    loadIcon().catch(err => console.error('加载图标失败:', err));
  }, []);

  return (
    <div>
      {imageSrc && <img src={imageSrc} alt="文件图标" />}
      {props.itemName}
    </div>
  )
}

export default Item

步骤3:可选方案——使用Tauri的asset协议

如果图标是应用打包时自带的资源,可将图标放在src/assets目录下,通过Tauri的asset协议加载:

// 假设图标放在src/assets/icons8-file-48.png
<img src="asset:///icons8-file-48.png" alt="文件图标" />

这种方式无需额外配置文件权限,但仅适用于打包时包含的静态资源。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.14 09:21:21