文件协议中文件 URI 的正确格式

Proper formatting of file URI in file protocol

所以我试图找出在不同系统上使用抓取文件时要使用的正确斜线数量。

我知道正确的格式是 file://hostname/path (https://en.wikipedia.org/wiki/File_URI_scheme#Format).

因为我只处理本地主机的文件,主机被省略了,但是将主机名与路径的其余部分分开的斜杠仍然存在,这给了我 file:///[path] 一切都很好,很容易找到例子。

然而,当在 OSX machine 上使用相同的软件时,我不知道如何正确格式化 URI,据我所知,斜线表示根 (http://www.westwind.com/reference/OS-X/paths.html) 这将使正确的格式:

file://localhost//[path from root]

省略主机名给我 file:////[path from root] 尽管我可以很容易地找到在 mac 环境中使用三个斜线的人的例子(这应该是不正确的?)。

在我的情况下,这两种解决方案似乎都有效,但这可能是因为 'incorrect' 一个在我不知情的情况下被更改为正确的解决方案,我不相信其他任何地方都会发生这种情况. 所以请有人给我解释一下,哪一个是正确的?

如果问题不好或属于其他地方,请告诉我。

我猜您是在问是否需要 URL 中的第一个 '/' 字符。答案可以在 3.10 of RFC 1738:

部分找到

The file URL scheme is used to designate files accessible on a
particular host computer. This scheme, unlike most other URL schemes, does not designate a resource that is universally accessible over the Internet.

A file URL takes the form:

   file://<host>/<path>

where <host> is the fully qualified domain name of the system on
which the <path> is accessible, and <path> is a hierarchical
directory path of the form <directory>/<directory>/.../<name>.

For example, a VMS file

 DISK$USER:[MY.NOTES]NOTE123456.TXT

might become

 <URL:file://vms.host.edu/disk$user/my/notes/note12345.txt>

As a special case, <host> can be the string "localhost" or the empty string; this is interpreted as `the machine from which the URL is being interpreted'.

The file URL scheme is unusual in that it does not specify an
Internet protocol or access method for such files; as such, its
utility in network protocols between hosts is limited.

文件 URL 方案与所有网络 url 方案的工作方式相同。主机规范在另一个 RFC 中处理。 VMS 示例使用 disk/user 说明符,即 non-standard。但是,在大多数 OSes(windows、unix、machos)中,一些参数是 隐含的,因此是空字符串:

一个fully-qualified文件url看起来像这样:

文件://用户:密码@host/path/to/file

用户、密码和主机通常对当前登录的用户和本地主机都是隐含的(除非文件系统允许用户在 URL 中指定权限)。协议说明符 (file://) 之后的所有内容都 relative 相对于(当前或指定的)主机上的(指定的或隐式的)用户。如果您从 URL 中剥离协议、用户和主机信息,您将留下一个标准 (unix) 路径。鉴于你对路径的了解,你可以用同样的方式对待它们(并正确地假设你的 OS 会做同样的事情):

  1. 前面有斜杠的路径是绝对路径来自user/host挂载的根目录 ,基本上是程序可见的文件系统层次结构中的最高级别 运行 作为当前主机上的当前用户:/path/to/file

  2. 前面没有斜线的路径是相对来自程序当前工作目录[的路径path/to/file

因此,您的文件 URL 的指定方式应与您在程序或 shell 脚本中指定路径的方式相同:

绝对值:file:///path/to/file 相对:file://path/to/file

在实践中,明智的做法是在运行时通过使用 绝对 定义的基目录将所有路径转换为绝对路径,并在转换为 [= 之前​​附加相对路径71=]。不建议文件 URLs 在机器之间传递,或者在目录可能更改的网络安装文件系统上使用,或者可能安装到动态位置(例如使用 automount)。它们应该只用于 user-defined 位置,或众所周知的 cross-host 文件系统位置。