HTML5文件API之圖片預覽
圖片上傳在當今的Web應用中是一個非常常用的功能,如果不需要在上傳前進行圖片預覽則可以簡單的使用HTML+Javascript來實現,但如果一定要在上傳之前提供圖片預覽功能則需要求助于Flash來實現。不過,隨著HTML5 File API的誕生這一狀況終于有了改觀,本文將介紹如何使用HTML5 File API快速的實現圖片預覽功能。
瀏覽器支持情況
本文實現的功能在以下瀏覽器中經過測試:IE8、Firefox3.6、Chrome6.0、Opera10、Safari4。其中Firefox3.6與Chrome6.0已經實現了該標準(雖然并沒有完全遵循標準),其他瀏覽器均未實現。關于具體的兼容性問題,后文將詳細說明。
文件選擇與獲取
如今最常見的文件選擇方式是使用File Input元素,用戶通過該元素打開本機文件對話框尋找并選擇相應的文件,不過隨著HTML5 Drag Drop API的出現又增加了一種新的方式-用戶可以直接將本機的文件拖拽到Web頁面中。
方式一<input type=”file”>
| <input id="fileSel" type="file"
onchange="handleFiles(this.files)"> <script type="text/javascript"> //獲取用戶選擇的文件 function handleFiles(files){ //遍歷files并處理 } </script> |
方式二 Drag & Drop
| <div id="fileDropRegion">將文件拖拽到此</div>
<script type="text/javascript"> //獲取用戶選擇的文件 var dr = document.getElementById('fileDropRegion'); dr.addEventListener("drop",function(e){ e.stopPropagation(); e.preventDefault(); var dt = e.dataTransfer; //獲取文件數組 var files = dt.files; handleFiles(files); },false); function handleFiles(files){ //遍歷files并處理 } </script> |
文件讀入與展示
通過上文中的方法我們獲取到了用戶選擇的文件數組,接下來就該操作其中的每一個文件了,如HTML5 File API描述的那樣,每個文件對象應該包含以下屬性:
|
readonly attribute DOMString name; //The name of the file. readonly attribute unsigned long long size; //Represents the size of the Blob object in bytes. readonly attribute DOMString type; //The media type of the Blob readonly attribute DOMString url; //The URL representing the Blob object. |
如果是上傳圖片則可以通過type屬性來進行圖片格式過濾,并可以通過size屬性來控制圖片大小。對于這些屬性,Firefox與Chrome的實現情況是出奇的一致,均只支持name、size和type屬性。
| function handleFiles(files){ //遍歷files并處理 for (var i = 0; i < files.length; i++) { var file = files[i]; var imageType = /image.*/; //通過type屬性進行圖片格式過濾 if (!file.type.match(imageType)) { continue; } //讀入文件 } } </script> |
此外,HTML5 File API中還定義了一個BlobReader,通過它可以使用各種不同的方式讀入文件并且可以監聽和處理讀取文件過程中的各個狀態。不過在Firefox與Chrome的實現中,并沒有這樣一個BlobReader,取而代之的是FileReader,擁有與BlobReader相同的方法和事件。
|
// async read methods void readAsArrayBuffer(in Blob blob); void readAsBinaryString(in Blob blob); void readAsText(in Blob blob, [Optional] in DOMString encoding); void readAsDataURL(in Blob blob); // event handler attributes attribute Function onloadstart; attribute Function onprogress; attribute Function onload; attribute Function onabort; attribute Function onerror; attribute Function onloadend; |
以上4個讀取文件的方式均是異步的,需要注冊監聽對應的事件來處理文件,而與圖片預覽相關的方法是readAsDataURL,該方法會將圖片文件內容轉換成dataURI的格式,而該格式是可以直接在瀏覽器中顯示的。
| function handleFiles(files){ //遍歷files并處理 for (var i = 0; i < files.length; i++) { var file = files[i]; var imageType = /image.*/; //通過type屬性進行圖片格式過濾 if (!file.type.match(imageType)) { continue; } //讀入文件 var reader = new FileReader(); reader.onload = function(e){ //e.target.result返回的即是圖片的dataURI格式的內容 var imgData = e.target.result, img = document.createElement('img'); img.src = imgData; //展示img } reader.readAsDataURL(file); } } </script> |
通過以上幾步便簡單的實現了圖片的上傳前的預覽功能,具體的效果請在Firefox或Chrome下打開此頁面。
參考資料