JavaScript implementation upload pictures and show

Time:2019-12-6

We all know that the image uploaded looks like this (before selection)It’s like this (after selection)

 

Set up image upload in HTML first

Upload pictures

Then edit the CSS Style

#file{
    display: none;
}
#file + label{
    display: inline-block;
    width: 100px;
    height: 30px;
    background-color: rgb(90, 152, 222);
    text-align: center;
    line-height: 30px;
    border-radius: 5px;
}
img{
    display: none;
    width: 200px;
    height: 200px;
}

Finally, set the changes after JS uploads the pictures

var myimg = document.getElementById('myimg');
var file = document.getElementById('file');
file.onchange = function(){
    var url;
    Var agent = navigator.useragent; // check browser version
    if (agent.indexOf("MSIE")>=1) {
      url = file.value;
    } else if(agent.indexOf("Firefox")>0) {
      url = window.URL.createObjectURL(file.files.item(0));
    } else if(agent.indexOf("Chrome")>0) {
      url = window.URL.createObjectURL(file.files.item(0));
    }
    myimg.src = url
    myimg.style.display = "block";
}

The final results are as follows: before selectionAfter selection

This article is a simple little white text. It only tells the knowledge points. If it helps, please do not copy it. Please modify and use it by yourself