问题
I was wondering if it's possible to read the content of a local directory, for instance C:\temp, using the html5 filesystem api or is it only possible access files/directories in the "sandboxed area"?
回答1:
The HTML5 file system is designed solely for sandboxed file storage, so no, you cannot use it to access files on the user's non-sandboxed file system.
回答2:
There is the drag and drop method example at MDN which works to display the file or folder name. If it's a directory, it lists the files in the directory and subdirectories.
This works on my local web server, at this MDN page, and in this fiddle - but isn't working in the snippet below except to display the file/folder name...
let dropzone = document.getElementById("dropzone");
let listing = document.getElementById("listing");
//handle files dropped in
function scanFiles(item, container) {
let elem = document.createElement("li");
elem.innerHTML = item.name;
container.appendChild(elem);
if (item.isDirectory) {
let directoryReader = item.createReader();
let directoryContainer = document.createElement("ul");
container.appendChild(directoryContainer);
directoryReader.readEntries(function(entries) {
entries.forEach(function(entry) {
scanFiles(entry, directoryContainer);
});
});
}
}
//prevent default dragover behavior
dropzone.addEventListener("dragover", function(event) {
event.preventDefault();
}, false);
//handle the drop event
dropzone.addEventListener("drop", function(event) {
let items = event.dataTransfer.items;
event.preventDefault();
listing.innerHTML = "";
for (let i=0; i<items.length; i++) {
let item = items[i].webkitGetAsEntry();
if (item) {
scanFiles(item, listing);
}
}
}, false);
#dropzone {
text-align: center;
width: 300px;
height: 100px;
margin: 10px;
padding: 10px;
border: 4px dashed red;
border-radius: 10px;
}
#boxtitle {
display: table-cell;
vertical-align: middle;
text-align: center;
color: black;
font: bold 2em "Arial", sans-serif;
width: 300px;
height: 100px;
}
body {
font: 14px "Arial", sans-serif;
}
<p>Drag files and/or directories to the box below!</p>
<div id="dropzone">
<div id="boxtitle">
Drop Files Here
</div>
</div>
<h2>Directory tree:</h2>
<ul id="listing">
</ul>
https://developer.mozilla.org/en-US/docs/Web/API/FileSystemDirectoryReader/readEntries#Example
来源:https://stackoverflow.com/questions/17243930/reading-local-files-directories-with-html5-filesystem-api