天天看點

html5 多檔案選擇

HTML5 裡面對于檔案上傳有了極大的增強,曾幾何時,當我們需要實作一個多檔案雙傳功能,必須一次指定多個<input type="file>,如果要上傳10個檔案就必須指定10行,因為HTML4 裡面,所有的<input type="file>隻支援單個檔案選擇、

但是在HTML5裡面,可以給<input type="file"> 加上一個multiple屬性,這樣這個空間就直接支援多檔案上傳了.廢話不多說,獻上代碼:

<!DOCTYPE html> 

<head> 

<meta charset="UTF-8"> 

<title>HTML5 對于多檔案選擇的增強Demo</title> 

<script type="text/javascript" src="js/fileops.js"></script> 

</head> 

<p>multiple檔案選擇 FileList Demo:</p> 

選擇檔案: 

<input type="file" id="multifile" multiple size="80"/> 

<input type="button" onclick="showFileName()" value="檔案上傳" /> 

當點選button時候,會觸發showFileName()方法,這裡将周遊所有被選擇的檔案,并且依次列印出它們的檔案名:

/** 

 *  This file is confidential by Charles.Wang 

 *  Copyright belongs to Charles.wang 

 *  You can make contact with Charles.Wang ([email protected]

 */ 

 function showFileName(){ 

    console.log(" FileList Demo:"); 

    var file; 

    //取得FileList取得的file集合 

    for(var i = 0 ;i<document.getElementById("multifile").files.length;i++){ 

        //file對象為使用者選擇的某一個檔案 

        file=document.getElementById("multifile").files[i]; 

        //此時取出這個檔案進行處理,這裡隻是顯示檔案名 

        console.log(file.name); 

    } 

 } 

然後當點選“選擇檔案”按鈕時,則會彈出一個對話框,讓你選擇,這時候,你可以按住Ctrl鍵并且點選滑鼠左鍵點住你想要的檔案,進而進行多檔案選擇。不少人都在這裡搞不明白為什麼不能選擇多個檔案。

html5 多檔案選擇

選中之後,點"打開”,則<input>輸入框中會提示你已經選擇了多少個檔案:

html5 多檔案選擇

最後,點選“檔案上傳”按鈕,則會觸發這段JS代碼的最終執行,它用FileList進行周遊所有被選擇的檔案,然後依次在浏覽器控制台列印出檔案名,于是,控制台輸出如圖:

html5 多檔案選擇