2017-05-22 57 views
1

我想弄清楚如何循環React JS中的多個文件上傳。多個文件上傳與React JS

最終,我希望能夠遍歷每個文件,以便我可以判斷是否僅上傳PNG,JPG和MP3文件。我還希望將PNG/JPG文件限制爲5MB,將MP3文件限制爲2MB。

到目前爲止,我無法弄清楚爲什麼我可以訪問一個文件而不是一個文件數組。

<input id="file" type="file" onChange={this.handleChange.bind(this)} required multiple /> 

我handleChange功能看起來是這樣的:

handleChange(event) { 
    const target = event.target; 
    const value = target.type === 'checkbox' ? target.checked : target.value; 

    this.setState({ 
     [id]: value 
    }); 

    console.log(id) 
    console.log(value) 
} 

當我選擇多個文件,我只得到一個顯示出來。例如,在兩個控制檯線以上產生以下:

file 
C:\fakepath\My Secret Document.docx 

爲什麼被存儲在value僅單個值?我怎樣才能正確地遍歷每個文件來檢查它的大小和類型?我對使用JQuery不感興趣。

+0

要檢查什麼是'event.target.files' –

+0

感謝@JoshuaTerrill,這就是我一直在尋找。 :) – kojow7

回答

3

這些文件包含在一個FileList中,在event.target.files之內,你可以做Array.from(event.target.files)並獲得了一個包含所有選中文件的數組。

更多有關FileList