亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

反應.js。當我嘗試使用 FileReader 上傳超過 3 個圖像文件時,只上傳了 3 個

反應.js。當我嘗試使用 FileReader 上傳超過 3 個圖像文件時,只上傳了 3 個

拉莫斯之舞 2023-06-09 15:52:21
下一個函數是獲取文件并將其設置為狀態 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);}
查看完整描述

1 回答

?
蕭十郎

TA貢獻1815條經驗 獲得超13個贊

確定找到了解決方案,所以我會分享它。將整個列表發送到 util 函數并在那里進行處理。在 util func 中,我將更新一個狀態,該狀態將是可選的加載文件。只有在檢查之后,我才會在組件內部設置“真實”圖像列表——這將在 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);

}


查看完整回答
反對 回復 2023-06-09
  • 1 回答
  • 0 關注
  • 165 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號