以HTML5的文件上傳API
如下demo代碼在.html文件打開即可:
!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>
一、input:file屬性
屬性值有以下幾個比較常用:
accept:表示可以選擇的文件MIME類型,多個MIME類型用英文逗號分開,常用的MIME類型見下表。
multiple:是否可以選擇多個文件,多個文件時其value值為第一個文件的虛擬路徑。
1、accept
只能選擇png和gif圖片
<input id="fileId1" type="file" accept="image/png,image/gif" name="file" />
2、multiple
多選文件上傳
<input id="fileId2" type="file" multiple="multiple" name="file" />
3、常用MIME類型
后綴名 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/