后端rust读取本地文件前端显示
1 目标
后端rust读取本地文件前端显示。
2 步骤
2.1 main.rs
// Prevents additional console window on Windows in release, DO NOT REMOVE!!
#![cfg_attr(not(debug_assertions), windows_subsystem = "windows")]
// Learn more about Tauri commands at https://tauri.app/v1/guides/features/command
#[tauri::command]
fn greet(name: &str) -> String {
format!("Hello, {}! You've been greeted from Rust!", name)
}
// 读取本地文件
use std::fs;
#[tauri::command]
fn read_text_file(path: String) -> Result<String, String> {
fs::read_to_string(&path).map_err(|err| err.to_string())
}
fn main() {
tauri::Builder::default()
.invoke_handler(tauri::generate_handler![greet,read_text_file])
.run(tauri::generate_context!())
.expect("error while running tauri application");
}
2.2 Greet.vue
<script setup lang="ts">
import { ref, onMounted } from "vue";
import { invoke } from "@tauri-apps/api/tauri";
import * as Cesium from 'cesium';
const greetMsg = ref("");
const name = ref("");
var viewer: Cesium.Viewer | null = null;
// 存储从后端读取的文件内容
const fileContent = ref("");
onMounted(async () => {
viewer = new Cesium.Viewer('cesiumContainer', {
terrain: Cesium.Terrain.fromWorldTerrain(), // 地形数据
});
// 获取文本文件内容并存储到 fileContent 中
fileContent.value = await getTextContent();
});
async function getTextContent() {
try {
// 读取本地文件内容
return await invoke("read_text_file", { path: 'C:\\test\\hello.txt' });
} catch (error) {
console.error("Failed to read the file:", error);
return "Error reading file";
}
}
async function greet() {
// Learn more about Tauri commands at https://tauri.app/v1/guides/features/command
greetMsg.value = await invoke("greet", { name: name.value });
}
</script>
<template>
<form class="row" @submit.prevent="greet">
<input id="greet-input" v-model="name" placeholder="Enter a name..." />
<button type="submit">Greet</button>
</form>
<p>{{ greetMsg }}</p>
<el-button type="primary">我是 ElButton</el-button>
<!-- 显示文件内容 -->
<el-text>{{ fileContent }}</el-text>
<el-container class="home-container">
<el-header>
</el-header>
<el-main>
<div id="cesiumContainer">
</div>
</el-main>
</el-container>
</template>
2.3 运行工程
npm run tauri dev
看到一下界面说明成功