第七色在线视频,2021少妇久久久久久久久久,亚洲欧洲精品成人久久av18,亚洲国产精品特色大片观看完整版,孙宇晨将参加特朗普的晚宴

為了賬號安全,請及時(shí)綁定郵箱和手機(jī)立即綁定
已解決430363個(gè)問題,去搜搜看,總會(huì)有你想問的

讀取文件為 base 64 以將其存儲(chǔ)到狀態(tài)變量中

讀取文件為 base 64 以將其存儲(chǔ)到狀態(tài)變量中

胡子哥哥 2021-10-14 10:59:45
我嘗試將輸入文件的 base64 值存儲(chǔ)到狀態(tài)變量中。但是,問題是獲取 base64 是異步的。所以我在 console.logs 中遇到了一些麻煩...這是我的代碼:getBase64(file) {        var reader = new FileReader();        reader.readAsDataURL(file);        reader.onload = function () {            arrayStamp.push({photo: reader.result})        };        reader.onerror = function (error) {          console.log('Error: ', error);        };    }handleFiles(event){        for(var x = 0; x < event.target.files.length; x++){            this.getBase64(event.target.files[x])        }        console.log(arrayStamp)        for(var x = 0; x < arrayStamp.slice.length; x++){            console.log(arrayStamp[x])        }    }這給了我:變量 arrayStamp 在類之前聲明,如下所示:let arrayStamp = []    class Photos extends Component {        constructor(props){            super(props)            this._child = React.createRef();            this.state = {                modalTitle: '',                alpha3: '',    ...我應(yīng)該如何瀏覽數(shù)組,它似乎是空的,但我在 console.log 中得到了值....我使用了一些庫,如 react-file-reader,但沒有人給我獲得原始文件 + base64 的可能性。
查看完整描述

2 回答

?
MM們

TA貢獻(xiàn)1886條經(jīng)驗(yàn) 獲得超2個(gè)贊

正如您所說,這是因?yàn)閞eadAsDataURL()是異步的,因此您必須等到所有文件都被讀取后才能使用您的數(shù)組。


const arrayStamp = [];


handleFiles(event) {

    let files = event.target.files,

        i = 0,

        reader = new FileReader();


    reader.onload = (e) => {

        arrayStamp.push({photo: reader.result})


        if (i++ < files.length - 1) {

            // Read the next file.

            reader.readAsDataURL(files[i]);

        } else {

            // All files have been read.

            console.log(arrayStamp);

        }

    };


    reader.readAsDataURL(files[i]);

}

我沒有測試過這個(gè),但應(yīng)該給你這個(gè)想法。本質(zhì)上,您使用一個(gè) fileReader 按順序加載每個(gè)文件并將結(jié)果推送到您的數(shù)組。


查看完整回答
反對 回復(fù) 2021-10-14
?
慕斯王

TA貢獻(xiàn)1864條經(jīng)驗(yàn) 獲得超2個(gè)贊

在函數(shù)目錄中


export function getBase64(img, callback) {

    const reader = new FileReader()

    reader.addEventListener('load', () => callback(reader.result))

    reader.readAsDataURL(img)

}

并使用這個(gè):


import { getBase64 } from 'functionsDirectory'


for (let i = 0; i < files.length; i++) {

  getBase64(

     files[i],

     base64 => { arrayStamp.push({base64, file: files[i]}) }

  )         

}


查看完整回答
反對 回復(fù) 2021-10-14
  • 2 回答
  • 0 關(guān)注
  • 334 瀏覽
慕課專欄
更多

添加回答

舉報(bào)

0/150
提交
取消
微信客服

購課補(bǔ)貼
聯(lián)系客服咨詢優(yōu)惠詳情

幫助反饋 APP下載

慕課網(wǎng)APP
您的移動(dòng)學(xué)習(xí)伙伴

公眾號

掃描二維碼
關(guān)注慕課網(wǎng)微信公眾號