【问题标题】:How to convert from a filename to a URL in Electron?如何在 Electron 中将文件名转换为 URL?
【发布时间】:2022-03-03 19:54:51
【问题描述】:

假设我得到一个 .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

你可以看到的是一个问题。网址将在#处截断。

This answer 声称我应该使用 encodeURI 但这也失败了,因为它使 # 未转义。

使用encodeURIComponent 也不起作用。它替换了/: 和空格,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]: 以及 UNC 路径的 \\

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

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

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

【问题讨论】:

标签: javascript electron


【解决方案1】:

您可以使用 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

【讨论】:

    【解决方案2】:

    这对我来说很好用:

    const open = require('open')
    const path = require('path')
    
    const FILE_NAME = 'картинка.jpg'
    const filePath  = path.join(__dirname, FILE_NAME)
    const fileUrl = `file:///${ filePath.split('\\').join('/') }`
    
    console.log(fileUrl)
    open(fileUrl)
    

    【讨论】:

    • 其实你不需要对你的 URL 进行编码就可以在本地打开它,我已经编辑了我的答案
    • Thakns 但该解决方案不像问题中指出的那样起作用。在 Windows 中。将文件命名为foo#bar.jpg。将其分配给问题中指定的图像。
    猜你喜欢
    • 2021-09-30
    • 1970-01-01
    • 2012-07-26
    • 2010-09-06
    • 2016-07-26
    • 1970-01-01
    • 1970-01-01
    • 2011-08-12
    • 1970-01-01
    相关资源
    最近更新 更多