Accessing Local Files with jQuery

2019-09-02 21:35发布

问题:

I believe that this question has been asked in a few different forms, but I've read quite a few different responses.

At first, I had a web-application written with mostly jQuery that would make use of servlets to retrieve information from various locations JavaScript could not access (ie. Feeds, images from a server, etc.). Now, however, I've been told to do away with the servlets and application configuration classes so that this project of mine contains only HTML, CSS, and JavaScript/jQuery. Rather than pulling the images off of the server, I need to retrieve them from a local file on the computer. I know that allowing this might seem like terrible design, but it's what I've been asked to do. At any rate, what I really need to do is count the number of image files in a directory and then perhaps compile an array of the filenames themselves. I could do this fine in Java when using the servlets, but without them, I'm not sure how or even if this can be done.

I'm basically trying to use the jQuery Cycle plug-in to cycle through these images like a slideshow. I inject (or $("#div").append()) these images into the div by using a loop based on the number of images present.

So, is there a way I can do this with using JavaScript, HTML, jQuery plug-in, etc? I'd like to avoid using PHP and Java at this point...

回答1:

You can't just read a directory with JavaScript; however, there appears to be a way to "exploit" how browsers function using http://www.irt.org/articles/js014/. It may not be pretty, but the demo works in the latest Chrome and IE7-9 for me. I'm sure some of the techniques could be updated to use cleaner code if you'd like to improve upon it.

EDIT: Another technique you could use can be found in Javascript read files in folder

It definitely looks to be a cleaner solution. What I'd recommend is extracting the body contents to inject into a hidden div or using the path for an iframe that you can read from.