skip to Main Content

My React component has the next code:

              <Row>
            <Col>
                <p>Select Image</p>
                <input type="file" name="myImage" onChange={this.handle_userImage_change} />                
            </Col>
            <Col>
                <img src={this.state.userImage} />
            </Col>

          </Row>

and also the next callback:

 handle_userImage_change = (event) => {
  console.log('handle_userImage_change>event=78658');
  console.log(event)
}

From the event parameter I want to get the file data to convert it to base64 using readAsDataUrl so later I can assign this value to

this.state.userImage

and in this way show the respective picture at the <img … > section.

a) What is the field from the event object I need to use?

b) Is the syntax correct for the <img ..> section?

2

Answers


  1. You can access the image data from files property in event.target object like this event.target.files[0]. files is an array and the image is stored as first element.

    You need to use URL.createObjectURL() to create an url representation of the image.
    You can store this in a state variable and then use it to pass to src prop of the image.

    const [image, setImage] = useState("");
    
    const handleFileUpload = (e) => {
      setImage(URL.createObjectURL(e.target.files[0]));
    };
    
    return <img src = {image} alt = "" / >

    Note that on chrome, if you re-upload the same image again when it is already selected, onChange event won’t trigger. Follow this to solve the issue.

    HTML input file selection event not firing upon selecting the same file.

    Login or Signup to reply.
  2. The above example is right but if you need to send the file/image to some backend service you might need to convert it into base64/blob.

    Here is the code to convert the file to base64.

    function getBase64(file) {
       var reader = new FileReader();
       reader.readAsDataURL(file);
    
       reader.onload = function () {
         console.log(reader.result);
       };
       reader.onerror = function (error) {
         console.log('Error: ', error);
       };
    }
    

    You can use base64 with img tag.

    All you have to do is include data:image/jpg;base64, infront of the base64 string. You can change jpg to whatever file type you want it to be

    <img src="data:image/jpg;base64,....."/>
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search