[英]React.js . when i am trying to upload more then 3 image files, using FileReader, only 3 uploaded
the next function is getting file and setting it in state obj (arr: [readerEvent.target.result]).下一个函数是获取文件并将其设置为状态 obj (arr: [readerEvent.target.result])。 works fine when uploading one file, fine with 2 and 3.上传一个文件时工作正常,2 和 3 都很好。
when I am trying to upload more then 3 files - only 3 uploaded .当我尝试上传超过 3 个文件时 - 只有 3 个上传 . I can see that the full (5) list of files is coming into the func by using console.log.通过使用 console.log,我可以看到完整的 (5) 文件列表正在进入 func。
input:
<Input
onChange={handleChange}
type="file"
// accept="image/png, image/jpeg"
multiple
/>
----------------------------------------
Component:
const list = Object.keys(e.target.files).map((elm) => e.target.files[elm]);
list.map((file, index) => {
loadFile(file, index, setImagesList);
});
---------------------------------------------------------------------------------------
Util:
export default function loadFile(file, index, setImagesList) {
// console.log("another file ", file);
let image = new Image();
var reader = new FileReader();
reader.onloadend = function (readerEvent) {
image.src = readerEvent.target.result;
image.onload = function () {
setImagesList((old) => [
...old,
{
key: `${Date.now()}-${file.name}-${index}`,
arr: [readerEvent.target.result],
imageOriginalWidth: image.width,
imageOriginalHeight: image.height,
},
]);
};
};
reader.onerror = function (event) {
console.error("File could not be read! Code " + event.target.error.code);
};
reader.readAsDataURL(file);
}
OK found a solution so I will share it.好的找到了解决方案,所以我会分享它。 sending to the util function the entire list and handle it there.将整个列表发送到 util 函数并在那里处理。 in util func I will update a state that will be the optional loaded file .在 util func 中,我将更新一个状态,该状态将是可选加载的文件。 only after a check I will set the "real" images list - that will happen out of the util - inside the component:只有在检查之后,我才会在组件内设置“真实”图像列表 - 这将发生在 util 之外:
useEffect(()=>{
uploaded.map((obj, index) => {
if (isValid) {
setImagesList((old) => [...old, obj]);
}
},[uploaded])
-----------------------------------
util :
export default function loadFiles(files, setUploaded) {
const reader = new FileReader();
let arr = [];
function readFile(index) {
if (index >= files.length || index > 5) {
setUploaded(arr);
return;
}
const file = files[index];
reader.onload = function (e) {
let image = new Image();
image.src = e.target.result;
image.onload = function () {
arr.push({
key: `${Date.now()}-${file.name}-${index}`,
name: file.name,
arr: [e.target.result],
imageOriginalWidth: image?.width,
imageOriginalHeight: image?.height,
});
readFile(index + 1);
};
};
reader.readAsDataURL(file);
}
readFile(0);
}
good luck!祝你好运!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.