javascript - 如何在 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\file
为c%3a\dir\file
然后似乎是电子的相对路径。
因此,我有更多特殊情况试图[a-z]:
在路径的开头检查 at 以及\\
UNC 路径。
今天我遇到了#
上面提到的问题,我期待更多的定时炸弹在等着我,所以我问......
以跨平台方式将文件名转换为 URL 的正确方法是什么?
或者更具体地说,如何解决上述问题。给定本地平台上图像文件绝对路径的目录列表,生成将加载这些图像的 URL(如果分配给图像的src
属性)。
解决方案
您可以使用 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
推荐阅读
- javascript - 如何在下面的 onClick 方法中运行 RowDataBound 方法?
- visual-studio-code - 更改 VSCode 小地图颜色
- arrays - 如何在python中将.dat文件转换为数组
- c# - c# File.Exists 总是使用 value 属性返回 false
- ruby-on-rails - 使用遥控器:真
- c# - 协议异常错误
- java - 如何使用光标获取所有联系人并将其存储在字符串中以将它们存储在firebase实时数据库中
- oracle-apex - Oracle APEX: scale image interactive report
- javascript - 将html5画布下载为pdf(safari浏览器)
- c# - AspNet.Core, IdentityServer 4: Unauthorized (401) during websocket handshake with SignalR 1.0 using JWT bearer token