目前关于这个主题的信息确实很少,所以我整理了一个例子,它结合了:
- 使用 上的
webkitdirectory
属性<input type="file">
。
- 使用文件系统 API。
- 这是关于沙盒文件系统,它允许您将文件存储在客户端机器上。
- 使用文件 API。
- 这是允许您读取文件的 API。这些文件可以通过一个
<input type="file">
元素、通过使用拖放的传输或通过 Filesystem API 来访问。
由于这些目前仅在 Chrome 中运行良好,因此我webkit
在必要时使用了前缀。
http://jsfiddle.net/zLna6/3/
代码本身有我希望清楚的注释:
var fs,
err = function(e) {
throw e;
};
// request the sandboxed filesystem
webkitRequestFileSystem(
window.TEMPORARY,
5 * 1024 * 1024,
function(_fs) {
fs = _fs;
},
err
);
// when a directory is selected
$(":file").on("change", function() {
$("ul").empty();
// the selected files
var files = this.files;
if(!files) return;
// this function copies the file into the sandboxed filesystem
function save(i) {
var file = files[i];
var text = file ? file.name : "Done!";
// show the filename in the list
$("<li>").text(text).appendTo("ul");
if(!file) return;
// create a sandboxed file
fs.root.getFile(
file.name,
{ create: true },
function(fileEntry) {
// create a writer that can put data in the file
fileEntry.createWriter(function(writer) {
writer.onwriteend = function() {
// when done, continue to the next file
save(i + 1);
};
writer.onerror = err;
// this will read the contents of the current file
var fr = new FileReader;
fr.onloadend = function() {
// create a blob as that's what the
// file writer wants
var builder = new WebKitBlobBuilder;
builder.append(fr.result);
writer.write(builder.getBlob());
};
fr.onerror = err;
fr.readAsArrayBuffer(file);
}, err);
},
err
);
}
save(0);
});
$("ul").on("click", "li:not(:last)", function() {
// get the entry with this filename from the sandboxed filesystem
fs.root.getFile($(this).text(), {}, function(fileEntry) {
// get the file from the entry
fileEntry.file(function(file) {
// this will read the contents of the sandboxed file
var fr = new FileReader;
fr.onloadend = function() {
// log part of it
console.log(fr.result.slice(0, 100));
};
fr.readAsBinaryString(file);
});
}, err);
});