我正在創建一個檔案上傳組件,我必須在其中只允許xls
或xlsx
檔案。我正在撰寫下面的代碼。
<div>
<form onSubmit={handleSubmit}>
<input type="file" accept="xlsx/*" required onChange={handleChange}/>
<button type="submit" className='submitbutton'>Import Bulk User</button>
</form>
</div>
但它不限制其他檔案型別。
如何限制其他檔案型別并只允許xlsx
uj5u.com熱心網友回復:
accept 屬性將一個或多個檔案型別或唯一檔案型別說明符的逗號分隔串列作為其值,用于描述允許的檔案型別:
<input type="file" accept=".xlsx, .xls" required onChange={handleChange}/>
uj5u.com熱心網友回復:
您仍然可以使用處理程式函式來驗證檔案擴展名。
獲取檔案擴展名
event.target.files[0].name.split(".")[1];
然后檢查它是否支持
if (allowedExtension.includes(fileExtension)) {
console.info("correct file uploaded!");
// set file to state
setUploadedFile(file);
} else {
console.error("incorrect file extension");
// show error
}
演示
uj5u.com熱心網友回復:
您應該更新輸入的accept
屬性,如下所示:
<input type="file" accept=".xls,.xlsx" required onChange={handleChange}/>
更多關于接受:https ://developer.mozilla.org/en-US/docs/Web/HTML/Attributes/accept
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/489890.html