js實現(xiàn)圖片上傳即時顯示效果
前言
h5實訓時實現(xiàn)的一個圖片上傳即時顯示的效果,如下圖所示

正文
Html代碼
<form action="" method="POST" role="form"> <div class="form-group"> <label for="touxiang" >頭像上傳:</label> <input type="file" id="headPhoto" name="headPhoto" /> <div ><img id="imag" src="img/up.png" alt="" style="height:5rem;width: 5rem;"></div> </div> </form>
js腳本代碼
<script>
/*顯示上傳的圖片*/
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 ;
}
$('#headPhoto').change(function() {
var eImg=$('#imag');
eImg.attr('src', getObjectURL($(this)[0].files[0]));
$(this).after(eImg);
});
</script>
window.URL.createObjectURL方法
創(chuàng)建一個新的對象URL,該對象URL可以代表某一個指定的File對象或Blob對象.
語法:
objectURL = window.URL.createObjectURL(blob);
blob參數(shù)是一個File對象或者Blob對象.
objectURL是生成的對象URL.通過這個URL,可以獲取到所指定文件的完整內容.
完整代碼如下:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>圖片上傳</title> <script src="https://cdn.bootcss.com/jquery/3.3.1/jquery.js"></script> <link href=https://cdn.bootcss.com/bootstrap/3.3.7/css/bootstrap.min.css rel="stylesheet"> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script> </head> <body> <form action="" method="POST" role="form"> <div class="form-group"> <label for="touxiang" >頭像上傳:</label> <input type="file" id="headPhoto" name="headPhoto" /> <div ><img id="imag" src="img/up.png" alt="" style="height:5rem;width: 5rem;"></div> </div> </form> </body> <script> /*顯示上傳的圖片*/ 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 ; } $('#headPhoto').change(function() { var eImg=$('#imag'); eImg.attr('src', getObjectURL($(this)[0].files[0])); $(this).after(eImg); }); </script> </html>
參考:鏈接
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持腳本之家。
相關文章
JavaScript requestAnimationFrame動畫詳解
這篇文章主要為大家詳細介紹了JavaScript requestAnimationFrame動畫,具有一定的參考價值,感興趣的小伙伴們可以參考一下2017-09-09
js實現(xiàn)iGoogleDivDrag模塊拖動層拖動特效的方法
這篇文章主要介紹了js實現(xiàn)iGoogleDivDrag模塊拖動層拖動特效的方法,實例分析了javascript操作拖動層的技巧,需要的朋友可以參考下2015-03-03

