js获取input上传的图片并预览


html 部分:

<div class="upload-pics-item small">
         <span class="iconfont upload-icon icon-xiangji f-20"></span>
         <input type="file" name="pic1" value="" class="upload-pic-input">
         <p class="f-12">添加图片</p>
          <img src="" alt="">
</div>

js 部分:

let dom = document.getElementsByClassName('upload-pic-input');
Array.from(dom).forEach(item=>{
  item.onchange = function(){
    $(this).parent().find('p').hide();
    $(this).parent().find('.iconfont').hide();
    let src = getObjectURL(this.files[0]);
    if(src){
      $(this).parent().find('img').attr('src',src);
    }else{
      $(this).parent().find('img').attr('alt',this.files[0]);
    }
  }
})

// 判断浏览器是否支持 createObjectURL api
function getObjectURL(file) {  
		 var url = null;   
		 if (window.createObjectURL!=undefined) {  
		  url = window.createObjectURL(file) ;  
		 } else if (window.URL!=undefined) { // mozilla(firefox)  
		  url = window.URL.createObjectURL(file) ;  
		 } else if (window.webkitURL!=undefined) { // webkit or chrome  
		  url = window.webkitURL.createObjectURL(file) ;  
		 }  
		 return url ;  
}


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM