Search code examples
javascriptreactjsmdbreact

Reactjs Input Upload doesn't return local URL


I have a problem when trying to display image preview before upload it to server. I 'm using reactjs.

My problem is when I try to upload an image I got the file data but when I'm using reader, it doesn't return local URL and just show undefined

this is the topic that I tried to follow get-image-preview-before-uploading-in-react

but when I try to check my image local url it return undefined

this is what I import in my file:

import React, {Component} from "react";
import { MDBContainer, MDBRow, MDBCol, MDBBtn, MDBIcon, MDBInput, MDBDropdown, MDBDropdownToggle, MDBDropdownMenu, MDBDropdownItem  } from 'mdbreact';

this is my js:

<p className="text-upload">Front Desain</p>
<input ref="file" type="file" name="front Design" onChange={this.frontDesign}/>

this is my method or function:

  frontDesign = (e) =>{
    var file = this.refs.file.files[0];
    var reader = new FileReader();
    var url = reader.readAsDataURL(file);

    reader.onloadend = function (e) {
        this.setState({
          form:{
            frontDesign: [reader.result]
          }
        })
      }.bind(this);
    console.log("Check Data : ", file)
    console.log("Check URL : ", url)

  }

and this is my state:

  state ={
    form:{
      frontDesign: [],
    }
  }

this is my console: What I got in my Console

This my codesandbox:

https://codesandbox.io/s/tender-mclaren-zb1l7?fontsize=14

can someone help me to solve this?


Solution

  • From the mozilla website it seams you need to add a load event listener to your reader. This sample code is not supported in some versions of IE.

    ...
    
    reader.addEventListener("load", () => {
      this.setState(state => ({
        ...state,
        form:{
          frontDesign: [reader.result]
        }
      }))
      const url = reader.result;
      console.log(url);
    }, false);
    
    ...
    

    Working condeSanbox here: https://codesandbox.io/s/affectionate-lamport-dnbij