URL.createObjectURL() 实现本地上传图片 并预览功能


URL.createObjectURL() 静态方法会创建一个 DOMString,其中包含一个表示参数中给出的对象的URL。这个 URL 的生命周期和创建它的窗口中的 document 绑定。这个新的URL 对象表示指定的 File 对象或 Blob 对象。

mdn传送门:https://developer.mozilla.org/zh-CN/docs/Web/API/URL/createObjectURL

 

 

<input class="avatarCon" type="file" />

<div class="showImg">
  <img src="" alt="" />
</div>

function getObjectURL(file) {
  var url = null;
  if (window.createObjectURL != undefined) {
    url = window.createObjectURL(file);
  } else if (window.URL != undefined) {
    url = window.URL.createObjectURL(file);
  } else if (window.webkitURL != undefined) {
    url = window.webkitURL.createObjectURL(file);
  }
  return url;
}

 

var avatarInput = $('.avatarCon');
avatarInput.change(function(event) {

  var myPic = $(this).get(0).files[0];

  $('.showImg img').attr('src',getObjectURL(myPic));
});

 


免责声明!

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



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