简体   繁体   中英

Javascript list files relative to root

This is for an offline application.

In html , we can access files relative to an html page. Eg:

  • <script src="scripts/jquery-3.3.1.min.js"></script>
  • <link rel='stylesheet' href='styles/style.css'>
  • <img src='./images/file1.jpg'/>

If I have many images in /images directory, is there a way to list all images in the directory using Javascript , or would I need to hard code the image names?

I'm asking specifically for using Javascript and without Node, running the files straight from Chrome.

Usually the client doesn't have access to the directory tree of the server. That means any client-side javascript, will not be able to list the directory tree.

You can configure apache to list the file-tree if there is no index file present, but usually that is frowned upon.

If you (against my recommendation) want to do this, you can configure apache to list the files and then fetch the file list with JavaScript.

A much better way to do this is to use server-side code (Node.js Server, PHP, etc.) which has access to the filesystem and can provide a list of files.

Local only application

Javascript usually doesn't have access to local resources and will throw a CORS error when trying to fetch normal resources. (The CORS error is thrown wether you're in a local directory already or not.) This makes this pretty much impossible to do without a webserver.

try run chrome.exe --allow-file-access-from-files

by running the command line above, it will enable http call using :

$.get("file:///url", function(data) {})

note that the data is returning string. if you append it into your html it will show the directory

Hand -coded not unless you use a web server (you don't need to install one, there are many tools to serve a single directory such as PHP or Python built-in servers).

But hard -coded yes: You can't access local filesystem from javascript, but your browser can if you type the ( file:// ) url in the navigation bar or follow a link pointing to it.

In case of links browsers refuse them in remote pages (from a web server) but not from files that are already local (otherwise you couldn't see a downloaded version of a web page).

I've never tested with absolute paths but (I think) it should work if you have permissions to that directory.

If not, there exists browser extensions, such as this one for Firefox that allows to open that links (if the user accepts it).

The problem is that, as I said, you need to put the links manually in the page and if there are so many it could take some time unless you are used to a real editors such as Vim or, at least, you are able to generate it using any programming language you like.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM