實現圖片上傳並顯示
阿新 • • 發佈:2019-01-28
實現效果:
預設會顯示一張自定義提示上傳圖片的預設圖片,點選圖片,實際上是點選input,然後進入圖片選擇步驟,選中圖片儲存後,選中的圖片就能替換預設圖片顯示出來。
html程式碼:
<label>圖片</label>
<div class="upload-img">
<input id="img-upload" type="file" name="img" accept="image/*">
<img id="img-show" src="預設圖片檔案路徑" class="img-polaroid" width="170" height="170" alt="上傳圖片" title="上傳圖片">
</div>
css樣式:
.upload-img{position:relative;}
.upload-img input{opacity: 0;border: 1px solid red;width: 177px;height: 164px;position: absolute;z-index: 1;}
jQuery程式碼:
<script type="text/javascript">
$('#img-upload').change(function(e) {
var input = $("#img-upload");
var file = input[0].files[0];//獲取input上傳的檔案
if(!file.name){
alert("未選擇圖片");
}else{
//高版本瀏覽器對檔案上傳路徑進行了安全處理,無法直接通過獲取input的value進行訪問,故轉化為獲取圖片的url進行安全訪問
var url = window.URL.createObjectURL(file);//將上傳的檔案轉化為url
$("#img-show" ).attr('src', url);//更新img的src屬性
};
});
</script>
過程收穫:
版本高的瀏覽器目前都支援本地檔案和瀏覽器分離。就本例項解釋就是,input上傳好檔案後,其value值並非直接顯示圖片在電腦中的位置,而是顯示如下:c:\fakepath\圖片名稱。故無法直接通過獲取input的value值實現圖片顯示。
以前一直以為js的document.getElementById(“container-id”)和jQuery的$(“#container-id”)等價,實際上前者返回的是HTMLDOM,而後者返回的是jQuery物件,兩者並不等價。但jQuery物件可以通過[index]或.get(index)來轉化為HTMLDOM,如程式碼所示。
淺顯地學習瞭如何實現圖片上傳功能。