Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to upload an image in React JS?

Tags:

reactjs

<div className="mb-1">
     Image <span className="font-css top">*</span>
     <div className="">
         <input type="file" id="file-input" name="ImageStyle"/>
     </div>
</div>

This is the snippet i provided that i was using to pick the file from the device in react js, Using this i can select the file and that filename is also shown as well What i want is now to store this file on S3 or anywhere and get its URL from there and POST it to my server using fetch api call.

like image 413
Piyush Avatar asked Apr 29 '17 06:04

Piyush


1 Answers

Upload the image from your file and display it on your page in react, you can also get the image object in the state when we select the image to display on the webpage you have to convert the image object to object using URL.createObjectURL(fileObject)

import React, { Component } from "react";

class DisplayImage extends Component {
  constructor(props) {
    super(props);
    this.state = {
      image: null
    };

    this.onImageChange = this.onImageChange.bind(this);
  }

  onImageChange = event => {
    if (event.target.files && event.target.files[0]) {
      let img = event.target.files[0];
      this.setState({
        image: URL.createObjectURL(img)
      });
    }
  };

  render() {
    return (
      <div>
        <div>
          <div>
            <img src={this.state.image} />
            <h1>Select Image</h1>
            <input type="file" name="myImage" onChange={this.onImageChange} />
          </div>
        </div>
      </div>
    );
  }
}
export default DisplayImage;
like image 150
ABHIJEET KHIRE Avatar answered Sep 20 '22 15:09

ABHIJEET KHIRE