首页 > 解决方案 > 如何在 Electron 中将文件名转换为 URL?

问题描述

假设我得到一个 .jpg 文件的目录列表,然后想要显示它们

const fs = require('fs');
fs.readDirSync(someAbsolutePathToFolder)
    .filter(f => f.endsWith('.jpg'))
    .forEach(filename => {
        const img = new Image();
        const filepath  = path.join(someAbsolutePathToFolder, filename);
        img.src = `file://${filepath.replace(/\\/g, '/')}`;
        document.body.appendChild(img);
    });

这将失败。举个例子,如果我得到的列表有这样的名字

#001-image.jpg
#002-image.jpg

上面的代码导致 URL 像

file://some/path/#001-image.jpg

你可以看到这是一个问题。URL 将在#.

这个答案声称我应该使用encodeURI,但这也失败了,因为它没有#转义。

使用encodeURIComponent也不起作用。它替换了/and:和空格,Electron 找不到该文件,至少在 Windows 上找不到。

到目前为止,我有这样的事情

const filepath  = path.join(someAbsolutePathToFolder, filename).replace(/\\/g, '/');
img.src = `file://${filepath.split('/').map(encodeURIComponent).join('/')}`;

但这在 Windows 上也失败了,因为驱动器号被转换c:\dir\filec%3a\dir\file然后似乎是电子的相对路径。

因此,我有更多特殊情况试图[a-z]:在路径的开头检查 at 以及\\UNC 路径。

今天我遇到了#上面提到的问题,我期待更多的定时炸弹在等着我,所以我问......

以跨平台方式将文件名转换为 URL 的正确方法是什么?

或者更具体地说,如何解决上述问题。给定本地平台上图像文件绝对路径的目录列表,生成将加载这些图像的 URL(如果分配给图像的src属性)。

标签: javascriptelectron

解决方案


您可以使用 Node 的 (v10+) pathToFileURL

import { pathToFileURL } from 'url';
const url = pathToFileURL('/some/path/#001-image.jpg');
img.src = url.href;

请参阅:https ://nodejs.org/api/url.html#url_url_pathtofileurl_path


推荐阅读