1 回答

TA貢獻(xiàn)1848條經(jīng)驗(yàn) 獲得超10個(gè)贊
我還必須以react-dropzone類似的方式驗(yàn)證每個(gè)文件。
我的解決方法是承諾FileReader.
1?? This is the promisified version of "FileReader"
const isValidFile = file => {
return new Promise((resolve, reject) => {
const reader = new FileReader();
reader.onloadend = evt => {
// other logic removed for brevity...
2?? Your custom logic dictates, if the file is valid or not
if (config.fileTypes.includes(type)) {
resolve(true);
} else {
resolve(false);
}
};
3?? Should there was an error, this file is not good.
reader.onerror = () => resolve(false)
4?? Start the reading process.
const blob = file.slice(0, 4);
reader.readAsArrayBuffer(blob);
});
};
現(xiàn)在您可以在for您提到的循環(huán)中使用它。
const onDropAccepted = useCallback(acceptedFiles => {
// reset to default state
resetToDefaultState();
1?? As `useCallback` accepts a non-async method,
Create a wrapped async method we can call here.
const processFiles = async () => {
if (config.isMultipleFiles === true) {
for (let i = 0; i < acceptedFiles.length; i++) {
const file = acceptedFiles[i];
2?? Here is where we validate the file using the code above.
const isValid = await isValidFile(file);
if (!isValid) {
setIsInvaildFileType(true);
return;
}
}
3?? At this point, all files are good.
setFiles([...files, ...acceptedFiles]);
} else {
// removed for brevity...
}
};
4?? Let's fire up the process
processFiles();
});
添加回答
舉報(bào)