Javascript 从本地文件夹中获取所有图像
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/30838871/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Get all images from local folder
提问by Alin
I need a way to get all the images from a local folder for a presentation that will also run locally. There will be no attempt for a server to take the images from a local folder since that is not possible/the case.
我需要一种从本地文件夹中获取所有图像的方法,以便在本地运行的演示文稿。服务器不会尝试从本地文件夹中获取图像,因为这是不可能的/这种情况。
I need to use .js since I can't use .php (which would be easier) since it runs on a local PC.
我需要使用 .js,因为我不能使用 .php(这会更容易),因为它在本地 PC 上运行。
Say I need to take all the images from learn/
说我需要从学习中获取所有图像/
I have tried various solutions that can be found here, hereand herebut none worked.
回答by Patrick Hofman
I think your best option is to use the new File API in Javascript. Is has a lot of functions to read files from the file system.
我认为您最好的选择是在 Javascript 中使用新的 File API。它有很多功能可以从文件系统中读取文件。
<input type="file" id="fileinput" multiple />
<script type="text/javascript">
function readMultipleFiles(evt) {
//Retrieve all the files from the FileList object
var files = evt.target.files;
if (files) {
for (var i=0, f; f=files[i]; i++) {
var r = new FileReader();
r.onload = (function(f) {
return function(e) {
var contents = e.target.result;
alert( "Got the file.n"
+"name: " + f.name + "n"
+"type: " + f.type + "n"
+"size: " + f.size + " bytesn"
+ "starts with: " + contents.substr(1, contents.indexOf("n"))
);
};
})(f);
r.readAsText(f);
}
} else {
alert("Failed to load files");
}
}
document.getElementById('fileinput').addEventListener('change', readMultipleFiles, false);
</script>
(code from here)
(来自这里的代码)
You can find a good explanation and helpful code here.
您可以在此处找到很好的解释和有用的代码。
回答by Alin
Thanks to Patrick Hofman's answer, I modified the code and ended up with this :
感谢帕特里克霍夫曼的回答,我修改了代码并最终得到了这个:
$(document).ready(function(){
function readMultipleFiles(evt) {
//Retrieve all the files from the FileList object
var files = evt.target.files;
if (files) {
for (var i=0, f; f=files[i]; i++) {
var r = new FileReader();
r.onload = (function(f) {
return function(e) {
var contents = e.target.result;
$('body').append('<h1>' + f.name + '</h1><img src="learn/' + f.name + '"/>');
};
})(f);
r.readAsText(f);
}
} else {
alert("Failed to load files");
}
}
document.getElementById('fileinput').addEventListener('change', readMultipleFiles, false);
});

