1

how to get the path of an uploaded file in reactjs. I use the file upload to upload a file

render() {
  return (
    <div>
      <input type="file" onChange={this.fileChangedHandler} />
      <button onClick={this.uploadHandler}>Upload!</button>
    </div>
  )
}

then bind the uploadHandler

this.uploadHandler = this.uploadHandler.bind(this)

and

uploadHandler = () => { 
  console.log("the selected file is : "+this.state.selectedFile.name)
}

Here I'm getting its name. I want to get the file path.

Rajat Jain
  • 1,155
  • 2
  • 12
  • 28
Renjith Stephen
  • 75
  • 1
  • 1
  • 8

1 Answers1

2

If you want to upload an image without posting to a server, you can use base64.

reactjs:

   this.state = {
     imgUpload: '',
   }

...

  this.getBase64 = this.getBase64.bind(this)

...

  getBase64(e) {
    var file = e.target.files[0]
    let reader = new FileReader()
    reader.readAsDataURL(file)
    reader.onload = () => {
      this.setState({
        imgUpload: reader.result
      })
    };
    reader.onerror = function (error) {
      console.log('Error: ', error);
    }
  }

...

  <div>
    <input type="file" className="input-file" name="imgUpload" accept='.png' onChange={this.getBase64} />
  </div>

Then you can use {this.state.imgUpload} to access the base64 string and can manipulate the image.

foureyedraven
  • 171
  • 3
  • 12