直接上代碼html
html代碼app
<div> <label>封面</label> <input type="file" id="cover" name="cover"> <img id="smallCover" width=200px height=200px> </div>
js代碼this
$('#cover').on('change',function(){ var filePath = $(this)[0].files[0].name //獲取到input的value,裏面是文件的路徑 fileFormat = filePath.split('.')[1].toLowerCase() src = window.URL.createObjectURL(this.files[0]) //轉成能夠在本地預覽的格式 // 檢查是不是圖片 if( !fileFormat.match(/png|jpg|jpeg/) ) { alert('上傳錯誤,文件格式必須爲:png/jpg/jpeg') return } $('#smallCover').attr('src',src) });
以上是上傳一張圖片並預覽spa
html就是一個類型是文件的input,下面放一個img用來預覽。code
js也很簡單就是當其圖片改變時轉成本地預覽格式,並判斷圖片後綴是否符合要求。orm
下面給出上傳多張並預覽htm
html代碼blog
<div> <label>圖片</label> <input type="file" id="picture" multiple/> </div> <div id="previewImg"> </div>
js代碼圖片
$('#picture').on('change', function(){ var imgFiles = $(this)[0].files for (i=0;i<imgFiles.length;i++){ filePath = imgFiles[i].name fileFormat = filePath.split('.')[1].toLowerCase() src = window.URL.createObjectURL(imgFiles[i]) if( !fileFormat.match(/png|jpg|jpeg/) ) { alert('上傳錯誤,文件格式必須爲:png/jpg/jpeg') return } var preview = document.getElementById("previewImg") var img = document.createElement('img') img.width = 200 img.height = 200 img.src = src preview.appendChild(img) } })
多張相似,只是多了個div,用for循環展現多張圖ip