1

As topic, I want get data:images after upload. I get that if only upload one image. If multiple images how to array it in console?

constructor(props) {
  super(props);
  this.state = {
    image: null
  };
}

onDropMain(mainImage) {
    var that = this
    let reader = new FileReader()
    reader.readAsDataURL(mainImage[0])
    reader.onloadend = function() {
        var result = reader.result
        that.setState({
            mainImage: result
        });
    }
    console.log(reader);
}

This is how I get single data:images, but how about multiple images? Anyone has experience in this?

Preview
  • 35,317
  • 10
  • 92
  • 112
Alan Yong
  • 993
  • 2
  • 12
  • 25

1 Answers1

2

To read multiple images:

1. First define a function that will read a single file.

2. Use any loop to call that function for each entry of the array.

3. Use array in state variable to store the result, instead of a single variable.

constructor(props) {
  super(props);
  this.state = {
    image: []
  };
}

Use this function to read multiple files:

onDropMain(mainImage) {
    var that = this;

    function read(file){
        let Reader = new FileReader();
        Reader.onload = function (event) {
            let image = that.state.image.slice();
            image.push(event.target.result);
            that.setState({image}, () => console.log(image));
        };
        Reader.readAsDataURL(file);
    }

    if (mainImage && mainImage.length) {
        [].forEach.call(mainImage, read);
    }    
}

Check the answers of this question for details about [].forEach.call(mainImage, read).

Preview
  • 35,317
  • 10
  • 92
  • 112
Mayank Shukla
  • 100,735
  • 18
  • 158
  • 142