以HTML5的文件上傳APIjavascript
以下demo代碼在.html文件打開便可:php
!DOCTYPE html> <html lang="zh_cn"> <head> <meta charset="UTF-8"> <title>HTML5文件上傳FileReader API</title> </head> <body> <!--一個能上傳多媒體文件的表單--> <input type="file" id="upload-file" multiple /> <!--顯示圖片的地方--> <div id="destination"></div> <script> document.getElementById('upload-file').addEventListener('change', function() { var file; var destination = document.getElementById('destination'); destination.innerHTML = '';//每次清空內容 // 循環用戶多選的文件 for(var x = 0, xlen = this.files.length; x < xlen; x++) { file = this.files[x]; console.log(file); if(file.type.indexOf('image') != -1) { // 很是簡單的交驗,判斷文件是不是圖片 var reader = new FileReader();//文件預覽對象 reader.readAsDataURL(file);//設置要預覽的文件 reader.onload = function(e) {//監聽文件加載完成事件 var img = new Image();//創鍵預覽圖片 img.src = e.target.result; //把預覽圖片的src設置爲e.target.result屬性。返回預覽文件的二進制內存數據 destination.appendChild(img);//在把每張圖片,放到預覽區域 }; } } }); </script> </body> </html>
屬性值有如下幾個比較經常使用:css
accept:表示能夠選擇的文件MIME類型,多個MIME類型用英文逗號分開,經常使用的MIME類型見下表。html
multiple:是否能夠選擇多個文件,多個文件時其value值爲第一個文件的虛擬路徑。java
只能選擇png和gif圖片ajax
<input id="fileId1" type="file" accept="image/png,image/gif" name="file" />
多選文件上傳json
<input id="fileId2" type="file" multiple="multiple" name="file" />
後綴名 MIME名稱 *.3gpp audio/3gpp, video/3gpp *.ac3 audio/ac3 *.asf allpication/vnd.ms-asf *.au audio/basic *.css text/css *.csv text/csv *.doc application/msword *.dot application/msword *.dtd application/xml-dtd *.dwg image/vnd.dwg *.dxf image/vnd.dxf *.gif image/gif *.htm text/html *.html text/html *.jp2 image/jp2 *.jpe image/jpeg *.jpeg image/jpeg *.jpg image/jpeg *.js text/javascript, application/javascript *.json application/json *.mp2 audio/mpeg, video/mpeg *.mp3 audio/mpeg *.mp4 audio/mp4, video/mp4 *.mpeg video/mpeg *.mpg video/mpeg *.mpp application/vnd.ms-project *.ogg application/ogg, audio/ogg *.pdf application/pdf *.png image/png *.pot application/vnd.ms-powerpoint *.pps application/vnd.ms-powerpoint *.ppt application/vnd.ms-powerpoint *.rtf application/rtf, text/rtf *.svf image/vnd.svf *.tif image/tiff *.tiff image/tiff *.txt text/plain *.wdb application/vnd.ms-works *.wps application/vnd.ms-works *.xhtml application/xhtml+xml *.xlc application/vnd.ms-excel *.xlm application/vnd.ms-excel *.xls application/vnd.