1 回答
![?](http://img1.sycdn.imooc.com/5458502c00012d4a02200220-100-100.jpg)
TA贡献1848条经验 获得超10个赞
我还必须以react-dropzone类似的方式验证每个文件。
我的解决方法是承诺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);
});
};
现在您可以在for您提到的循环中使用它。
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();
});
添加回答
举报