【发布时间】:2013-06-08 20:36:19
【问题描述】:
在 javascript/jquery 中,给定一个 url 字符串,如何检查它是文件还是目录的 url?
谢谢
【问题讨论】:
标签: javascript jquery file url path
在 javascript/jquery 中,给定一个 url 字符串,如何检查它是文件还是目录的 url?
谢谢
【问题讨论】:
标签: javascript jquery file url path
只是为了更新一个支持字符串的版本,你可以在 JavaScript 中使用内置的URL 函数(除非你在
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"
【讨论】:
就像大卫说的,你真的说不出来。但是如果你想知道一个 url 的最后部分是否有一个 '.'在其中(也许这就是您所说的“文件”的意思?),这可能有效:
function isFile(pathname) {
return pathname.split('/').pop().indexOf('.') > -1;
}
function isDir(pathname) { return !isFile(pathname); }
console.log(isFile(document.location.pathname));
【讨论】:
https://something.com/dl/file/1234
你不能,因为 HTTP 没有区别。
网址既不是“文件”也不是“目录”。这是一个资源。当请求该资源时,服务器会响应一个响应。该响应由标头和内容组成。
标头(例如content-disposition)可能表明响应应该由消费客户端处理作为文件。但它本身并不是一个“文件”,因为 HTTP 不是一个文件系统。
并且任何资源都可以返回服务器想要的任何响应。例如,您可能会请求 http://www.something.com 并期望不会获得文件,因为您没有请求文件。但它仍然可以返回一个。或者,即使您请求index.html,您也可能不会得到一个名为“index.html”的“文件”,而是得到一些其他响应。
即使您从您的角度要求“目录”,服务器仍会以标题和内容进行响应。该内容可能采用目录列表的形式,但除了解析内容本身之外,它与任何其他成功响应没有区别。
如果您正在查找服务器指示为“文件”的内容,那么您正在查找响应中的 content-disposition 标头,并且您需要解析该标头的值。除了这种情况,我怀疑无论您需要知道它是“文件”还是“目录”,这都是您尝试做的任何设计问题的症状,因为问题本身没有实际意义在 HTTP 中。
【讨论】: