JS to upload the image and display the name of the image

Time:2021-5-12

This example for you to share the JS upload image and display the specific code of the image name, for your reference, the specific content is as follows

Today, I sorted out the upload map. It’s more convenient to use jQuery. The little girl sorted out the native JS!!!

<!DOCTYPE html>
<html>
<head lang="en">
 <meta charset="UTF-8">
 <title></title>
 <style>
  img{max-width: 100%; height: 100px;margin: 10px 20px;}
  .img_list .img-div{width: 100px;height: 200px; float: left; overflow: hidden;text-align: center; }
  .upload{position: relative;}
  .upload input{opacity: 0;position: absolute;top: 0;left: 10px;height: 100px;width: 100px;}
  .upload .upload_box{width: 100px;height: 100px;background-color: pink;color: white;}
  .img-div p{color: #28a4b0;margin: 0;}
 </style>
</head>
<body>
<div>
 <input type="file" multiple/>
 <div>
  Click me to upload pictures
 </div>
 
</div>
 
<div>
 
</div>
<script>
 var file_input=document.getElementsByClassName("file_input")[0];
//The trigger event uses change, because files is an array and subscripts need to be added
 file_input.addEventListener("change",function(){
  var obj=this;
  var obj_name=this.files[0].name;
  var img_length=obj.files.length;
  for(var i=0;i<img_length;i++)
  {
   if(!(/image\/\w+/).test(obj.files[i].type))
   {
    Alert ("upload image format error, please upload image");
    return false;
   }
   var reader = new FileReader();
   reader.error=function(e){
    Alert ("read exception")
   }
   reader.onload = function(e){
//    div_ Html is a container that includes images and image names
    var img_html='<img src="'+e.target.result+'"/>';
    var div_html=document.createElement("div");
    var p_html=document.createElement("p");
    if(document.getElementsByClassName("img_list")[0].children.length<5)
    {
     div_html.innerHTML=img_html;
     div_html.appendChild(p_html);
     p_html.innerHTML=obj_name;
     div_html.className="img-div";
     document.getElementsByClassName("img_list")[0].appendChild(div_html);
    }else{
     Alert ("upload up to 5 pictures")
    }
   };
   reader.οnlοadstart=function(){
    Console.log ("start reading" + obj_ name);
   }
   reader.οnprοgress=function(e){
    if(e.lengthComputable){
     Console.log ("reading file")
    }
   };
   reader.readAsDataURL(obj.files[i]);
  }
 
 })
</script>
</body>
</html>

For more wonderful content, please refer to the topic “Ajax upload technology summary”, “JavaScript file upload operation summary” and “jQuery upload operation summary” for learning.

The above is the whole content of this article, I hope to help you learn, and I hope you can support developer more.