Reputation: 23
I am trying to load images from a local directory using jQuery, I get this error:
file:///Users/[username]/Desktop/the/pics/Failed to load resource: Failed to load resource: file is directory
I am trying to use jquery to arrange a bunch of pictures on a page, in the same size next to each other.
I have an index file on the desktop with the image folder on the desktop as well within /the/pics directory. The index file looks as follows:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Images</title>
<script src="http://code.jquery.com/jquery-3.2.1.js" integrity="sha256-DZAnKJ/6XZ9si04Hgrsxu/8s717jcIzLy3oi35EouyE=" crossorigin="anonymous"></script>
<script>
var dir = "the/pics/";
var fileextension = ".jpeg";
$.ajax({
url: dir,
success: function(data) {
$(data).find("a:contains(" + fileextension + ")").each(function() {
var filename = this.href.replace(window.location.host, "").replace("http://", "");
$("body").append("<div class=\"crop\" ><img src='" + dir + filename + "'></div>");
});
}
});
</script>
<style>
body {
max-width: 960px;
margin: 0 auto;
}
.crop {
width: 200px;
height: 150px;
overflow: hidden;
}
.crop img {
width: 400px;
height: 300px;
margin: -75px 0 0 -100px;
}
</style>
</head>
<body>
</body>
</html>
Upvotes: 2
Views: 1793
Reputation: 6793
When it comes to processing local files from javascript, there are a lot of security means that get involved here. For example, you can only read files from several folders (e.g., you won't even have access to to %WINDOWS%\Fonts in a file upload browser window at least in Firefox 55).
This gets even more restrictive when this javascript resides in a local file rather than in a website served via HTTP. This prevents attack vectors where a simple piece of HTML gets written to your disk (e.g. your cache) and then accidentally or maliciously executed.
Although it sounds counterintuitive: Scripts residing in local html files have the least privileges.
One of the reasons is the Same-Origin Policy which states that only those resources are trustworthy that are served from the same webserver for the same domain. (In fact, it states a little bit more, including how to whitelist resources etc.)
But fact is: Each file on the hard drive is taken as a distinct location, this includes the image files, as there are no domains where these files could belong to. And this means: No script access on local images.
All in all it is a pretty good security measure, provided that it is implemented correctly.
The only thing you can do in this case is: Make sure your script (and the html page it is located in) is served via http. If necessary, use your hosts
-file to add local domains you need to address or set up an own dns server.
Upvotes: 2
Reputation: 491
Heyo,
The browser blocks it for security reasons Same-Origin Policy.
You can use just a simple python http server to have a static server
just run this line inside the folder you want to serve
python -m SimpleHTTPServer
Upvotes: 0