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));
});

 

转载于:https://www.cnblogs.com/xiaomaotao/p/7161603.html