2

在 javascript/jquery 中,给定一个 url 字符串,我如何检查它是文件还是目录的 url?

谢谢

4

3 回答 3

9

你不能,因为 HTTP 没有区别。

URL 既不是“文件”也不是“目录”。这是一种资源。当请求该资源时,服务器会响应一个响应。该响应由标题和内容组成。

标头(例如content-disposition)可能指示响应应该被消费客户端视为文件。但它本身并不是一个“文件”,因为 HTTP 不是一个文件系统。

并且任何资源都可以返回服务器想要的任何响应。例如,您可能会请求http://www.something.com并期望不会获得文件,因为您没有请求文件。但它仍然可以返回一个。或者,即使您提出要求,index.html您也可能不会得到一个名为“index.html”的“文件”,而是得到其他一些响应。

即使您从您的角度要求“目录”,服务器仍会以标题和内容进行响应。该内容可能采用目录列表的形式,但除了解析内容本身之外,它与任何其他成功响应没有区别。

如果您正在查找服务器指示为“文件”的内容,那么您正在查找content-disposition响应中的标头,并且您需要解析出该标头的值。除了这种情况,我怀疑无论您需要知道它是“文件”还是“目录”,这都是您尝试做的任何设计问题的症状,因为问题本身没有实际意义在 HTTP 中。

于 2013-06-12T16:23:04.907 回答
9

就像大卫说的,你真的说不出来。但是如果你想知道一个 url 的最后部分是否有一个 '.' 在其中(也许这就是您所说的“文件”的意思?),这可能有效:

function isFile(pathname) {
    return pathname.split('/').pop().indexOf('.') > -1;
}

function isDir(pathname) { return !isFile(pathname); }

console.log(isFile(document.location.pathname));
于 2013-06-12T16:24:06.680 回答
1

只是为了更新与字符串一起使用的版本,您可以使用URLJavaScript 中的内置函数(除非您在 <IE11 中)。正如我之前提到的那样,它在很多情况下都不起作用,这只是.在字符串 url 的文件名中检查 a 的粗略技巧。

const checkIfFile = (url) => {
  url = new URL(url);
  return url.pathname.split('/').pop().indexOf('.') > 0;
}

const urls = [
  "http://example.com",
  "http://example.com?v=1",
  "http://example.com/no",
  "http://example.com/no?no=3.1",
  "http://example.com/yes.jpg?yes=3.1",
  "http://example.com/yes.jpg",
  "http://example.com/maybe.someone.did.this/yes.jpg",
  "http://example.com/maybe.someone.did.this/",
];

urls.forEach(url => {
    console.log("The url " + url + " is " + (checkIfFile(url) ? "true" : "false"));
})

输出以下内容:

"The url http://example.com is false"
"The url http://example.com?v=1 is false"
"The url http://example.com/no is false"
"The url http://example.com/no?no=3.1 is false"
"The url http://example.com/yes.jpg?yes=3.1 is true"
"The url http://example.com/yes.jpg is true"
"The url http://example.com/maybe.someone.did.this/yes.jpg is true"
"The url http://example.com/maybe.someone.did.this/ is false"
于 2021-04-07T16:36:56.793 回答