1. 程式人生 > >vue html jq 實現上傳圖片顯示在頁面上預覽

vue html jq 實現上傳圖片顯示在頁面上預覽

1、html程式碼
<img src="" alt="" id="myimg">
<input type="file" name="fileToUpload" id="fileToUpload" 
 @change='changeimage($event)'>

注意這裡面定義的方法changeimage

2、script程式碼寫在methods裡面
getObjectURL(file) {  
var url = null ;   
 // 下面函式執行的效果是一樣的,只是需要針對不同的瀏覽器執行不同的 js 函式而已  
 if (window.createObjectURL!=undefined) { // basic  
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 ; }, changeimage (event
) { // 呼叫上面的方法 var objurl = this.getObjectURL(event.target.files[0]) console.log(objurl) $('#myimg').attr('src',objurl) }