刚入门学习js,主要是兴趣使然,想做一个打开任意的文件夹,显示里面的照片文件,由于js不能获取绝对路径,使用
FileReader进行显示照片,具体代码如下:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>读取文件显示图片</title>
</head>
<style>
*{
margin: 0px;
padding: 0px;
}
img{
width:100px;
height:500px;
min-height: 100%;
width: auto;
max-width:100%;
max-height:100%;
}
button{
width: 100px;
height: 30px;
border-radius: 5px;
background: green;
color: #fff;
margin:12%;
margin-top: 1%;
}
</style>
<body>
<br>
<br>
<br>
<br>
<br>
<input type="file" id="fileInput" onchange="selectFolder()" webkitdirectory directory multiple>
<div style="text-align:center">
<span style="color:blue;font-size:20px;" id="sp"><b></b></span>
</div>
<br>
<div class="container" style="text-align:center">
<img id="pic" src="">
<br>
<button id='prev' onclick="prev()">上一张</button>
<button id='next' onclick="next()">下一张</button>
</div>
<div id="result"></div>
<script language="javascript">
//读取图片类型
function selectFolder() {
var inputBox = document.getElementById("fileInput");
var index = 0;
var imgext = new Array("png","jpg","jpeg","bmp","gif");
var files = inputBox.files;
var ss = [];
for (var i = 0; i < files.length; i++) {
//判断是不是图片文件,不是的话不存入ss
var ind= files[i].name.split(".")[1];
//判断是不是包含图片文件
if (imgext.includes(ind)){
console.log(files[i]);
ss.push(files[i]);
}
}
//将局部变量ss变为全局变量
globalss = ss;
globalindex = index;
if (ss.length==0){
alert('没有照片文件!')
}
else{
document.getElementById("sp").innerHTML = 1+"/"+globalss.length;
var reader = new FileReader();
globalreader = reader;
reader.readAsDataURL(ss[0]);//发起异步请求
reader.onload = function()
{
pic.src = this.result;
//读取完成后,数据保存在对象的result属性中this.result就是reader.readAsDataURL(ss[0])
console.log(this.result)
}
}
}
function prev(){
//判断index是不是大于0
if (globalindex>0){
globalindex = globalindex-1
globalreader.readAsDataURL(globalss[globalindex]);
document.getElementById("pic").src=this.result;
document.getElementById("sp").innerHTML = globalindex+1+"/"+globalss.length;
}
else{
alert('这是第一张图片!')
}
}
function next(){
globalindex = globalindex+1
//alert(index);
//判断index是不是大于ss的长度
if (globalindex>=globalss.length){
alert('已经是最后一张图片了!')
}
else{
globalreader.readAsDataURL(globalss[globalindex]);
document.getElementById("pic").src=this.result;
document.getElementById("sp").innerHTML = globalindex+1+"/"+globalss.length;
}
}
</script>
</body>
</html>