the next function is getting file and setting it in state obj (arr: [readerEvent.target.result]). works fine when uploading one file, fine with 2 and 3.
when I am trying to upload more then 3 files - only 3 uploaded . I can see that the full (5) list of files is coming into the func by using console.log.
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. in util func I will update a state that will be the optional loaded file . only after a check I will set the "real" images list - that will happen out of the util - inside the component:
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!
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.