在 Electron 中,您可以通过自定义协议来读取本地图片文件并展示
第一种方案是将文件变为base64,但是如果文件多的话,会使页面的性能变卡顿
第二种方案:在 app
的 ready
事件中,使用 protocol.registerFileProtocol()
方法来注册自定义协议:
app.whenReady().then(() => {
// 注册自定义协议,例如 'myapp'
protocol.registerFileProtocol('myapp', (request, callback) => {
const url = request.url.substr(8); // 去掉协议头 'myapp://'
const decodedUrl = decodeURIComponent(url); // 解码 URL
try {
// 返回图片的本地路径
return callback(decodedUrl);
} catch (error) {
console.error('Failed to register protocol', error);
}
});
// 创建窗口等其他操作
createWindow();
});
注册获取文件的事件
ipcMain.handle('get-images', async (event, dirPath) => {
const imageExtensions = ['jpg', 'jpeg', 'png', 'webp'];
const files = fs.readdirSync(dirPath);
const images = files.filter((file) =>
imageExtensions.includes(extname(file).toLowerCase().slice(1)))
.map((file) => {
return {src: `${dirPath}/${file}`}
});
return images;
})
在vue中使用
const handleGetFile = async (folderPath: string) => {
return await ipcRenderer.invoke("get-images", folderPath);
}
onMounted(async () => {
const directory = localStorage.getItem('lastOpenDirectory') || '';
if (directory) {
breadCrumb.value = directory?.split('/') ?? [];
files.value = await handleGetFile(directory);
files.value = files.value.map((file: any) => {
return {src: `myapp:///${file.src}`}})
.....
}})