反应.js。当我尝试使用 FileReader 上传超过 3 个图像文件时,只上传了 3 个

下一个函数是获取文件并将其设置为状态 obj (arr: [readerEvent.target.result])。上传一个文件时工作正常,上传 2 和 3 时正常。


当我尝试上传超过 3 个文件时 - 只上传了 3 个。 我可以看到完整的 (5) 个文件列表正在通过使用 console.log 进入 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);

}


拉莫斯之舞
浏览 141回答 1
1回答

萧十郎

确定找到了解决方案,所以我会分享它。将整个列表发送到 util 函数并在那里进行处理。在 util func 中,我将更新一个状态,该状态将是可选的加载文件。只有在检查之后,我才会在组件内部设置“真实”图像列表——这将在 util 之外发生:&nbsp;useEffect(()=>{&nbsp; &nbsp;uploaded.map((obj, index) => {&nbsp; &nbsp; &nbsp; if (isValid) {&nbsp; &nbsp; &nbsp; &nbsp; setImagesList((old) => [...old, obj]);&nbsp; &nbsp; &nbsp; }},[uploaded])-----------------------------------util :export default function loadFiles(files, setUploaded) {&nbsp; const reader = new FileReader();&nbsp; let arr = [];&nbsp; function readFile(index) {&nbsp; &nbsp; if (index >= files.length || index > 5) {&nbsp; &nbsp; &nbsp; setUploaded(arr);&nbsp; &nbsp; &nbsp; return;&nbsp; &nbsp; }&nbsp; &nbsp; const file = files[index];&nbsp; &nbsp; reader.onload = function (e) {&nbsp; &nbsp; &nbsp; let image = new Image();&nbsp; &nbsp; &nbsp; image.src = e.target.result;&nbsp; &nbsp; &nbsp; image.onload = function () {&nbsp; &nbsp; &nbsp; &nbsp; arr.push({&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; key: `${Date.now()}-${file.name}-${index}`,&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; name: file.name,&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; arr: [e.target.result],&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; imageOriginalWidth: image?.width,&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; imageOriginalHeight: image?.height,&nbsp; &nbsp; &nbsp; &nbsp; });&nbsp; &nbsp; &nbsp; &nbsp; readFile(index + 1);&nbsp; &nbsp; &nbsp; };&nbsp; &nbsp; };&nbsp; &nbsp; reader.readAsDataURL(file);&nbsp; }&nbsp; readFile(0);}
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript