HTML5 reading local file sample code

Time:2022-5-29

The HTML structure style is as follows:

Copy code

The codes are as follows:

<div>
<button> add picture </button>
<form>
<input type=”file” multiple accept=”image/*” name=”logo”>
</form>
</div>
<img src=”” alt=””>

In terms of style, the input box of the input element should not be displayed. In this case, it is necessary to set the input to the transparent style, and then overlay it over the button element. Then, click the button to upload the image. If accepted is set to “image/*”, only picture files can be uploaded.

CSS style is as follows

Copy code

The codes are as follows:

.addpic{
position:relative;
margin-left:100px;
width:95px;
height:30px;
}
.addlogo {
background: none repeat scroll 0 0 rgba(0, 0, 0, 0);
cursor: pointer;
font-size: 30px;
opacity: 0;
position: absolute;
right: 0;
top: 0;
z-index: 10;
}

JS code

Copy code

The codes are as follows:

function readFiles(evt){
var files=evt.target.files;
if(!files){
console.log(“the file is invaild”);
return;
}
for(var i=0, file; file=files[i]; i++){
var imgele=new Image();
var thesrc=window.URL.createObjectURL(file);
imgele.src=thesrc;
imgele.onload=function(){
$(“#showlogo”).attr(“src”,this.src);
}
}
}
Copy code

The codes are as follows:

$(document).ready(function(){
$(“#logoimg”).change(function(e){
readFiles(e)
});
});