How to check if a url is a file or folder in javascript?

末鹿安然 提交于 2020-12-13 11:17:10

问题


In javascript/jquery, given a string of a url, how can I check if it is a url to a file or a directory?

Thanks


回答1:


You can't, because there's no difference in HTTP.

A URL is neither a "file" nor a "directory." It's a resource. When requesting that resource, the server responds with, well, a response. That response consists of headers and content.

A header (such as content-disposition) may indicate that the response should be treated as a file by the consuming client. But in and of itself it's not a "file" because HTTP is not a file system.

And any resource can return any response that the server wants. For example, you might request http://www.something.com and expect not to get a file because you didn't ask for one. But it can still return one. Or, even if you ask for index.html you might not get a "file" called "index.html" but instead some other response.

Even if you ask for a "directory" from your point of view, the server is still responding with headers and content. That content may take the form of a directory listing, but it's indistinguishable from any other successful response aside from parsing the content itself.

If you're looking for something which the server has indicated is a "file" then you're looking for the content-disposition header in the response and you'll want to parse out the value of that header. Other than that one case, I'd suspect that whatever need you have to know if it's a "file" or a "directory" is a symptom of a design problem in whatever you're trying to do, since the question itself is moot in HTTP.




回答2:


Like David said, you can't really tell. But if you want to find out if the last part of a url has a '.' in it (maybe that's what you mean by a "file"?), this might work:

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

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

console.log(isFile(document.location.pathname));


来源:https://stackoverflow.com/questions/17070465/how-to-check-if-a-url-is-a-file-or-folder-in-javascript

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!