Piyush
Piyush

Reputation: 1193

How to upload an image in React JS?

<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.

Upvotes: 50

Views: 220404

Answers (6)

ABHIJEET KHIRE
ABHIJEET KHIRE

Reputation: 2471

import React, { useState } from "react";

// Define a functional component named UploadAndDisplayImage
const UploadAndDisplayImage = () => {
  // Define a state variable to store the selected image
  const [selectedImage, setSelectedImage] = useState(null);

  // Return the JSX for rendering
  return (
    <div>
      {/* Header */}
      <h1>Upload and Display Image</h1>
      <h3>using React Hooks</h3>

      {/* Conditionally render the selected image if it exists */}
      {selectedImage && (
        <div>
          {/* Display the selected image */}
          <img
            alt="not found"
            width={"250px"}
            src={URL.createObjectURL(selectedImage)}
          />
          <br /> <br />
          {/* Button to remove the selected image */}
          <button onClick={() => setSelectedImage(null)}>Remove</button>
        </div>
      )}

      <br />

      {/* Input element to select an image file */}
      <input
        type="file"
        name="myImage"
        // Event handler to capture file selection and update the state
        onChange={(event) => {
          console.log(event.target.files[0]); // Log the selected file
          setSelectedImage(event.target.files[0]); // Update the state with the selected file
        }}
      />
    </div>
  );
};

// Export the UploadAndDisplayImage component as default
export default UploadAndDisplayImage;

Upvotes: 79

Utku AKTAS
Utku AKTAS

Reputation: 125

Failed to execute 'createObjectURL' on 'URL': Overload resolution failed.

For some reason I coudn't use URL.createObjectURL(image) as

  const [image, setImage] = useState(null);
  const [imgURL, setImgURL] = useState();

<img src={URL.createObjectURL(image)}/>

So I save the Url in the state for instant display on the button click method. This worked!

setImgURL(URL.createObjectURL(image)); 

Unfortunately, I was still getting the same error when I use useEffect.

  useEffect(() => {
    setImgURL(URL.createObjectURL(image));
  }, [image]);

Upvotes: 0

Vinci
Vinci

Reputation: 1286

This code let you upload image to the server,the backend code is written in nestjs,and display the image which will be uploaded.I have used the formdata.

import React, { useEffect, useState } from "react";
function Product() {

    const { REACT_APP_REST } = process.env;

    const [file, setFile] = useState([]);

    const handleFile = event => {
        setFile(
            URL.createObjectURL(event.target.files[0])
        );
        const formData = new FormData();
        formData.append("fileupload", event.target.files[0]);

        fetch(REACT_APP_REST + "/product/upload", {
            method: 'POST',

            body: formData,
            dataType: "jsonp"
        })
    };
    return (
        <>
            <Container fluid>
                <Col md="4">
                    <Card className="card-user">
                        <img src={file} />
                        <Card.Body>
                            <Form.Group>
                                <label>IMAGE</label>
                                <Form.Control
                                    type="file"
                                    required="required"
                                    onChange={handleFile}
                                ></Form.Control>
                            </Form.Group>
                        </Card.Body>
                        <hr></hr>

                    </Card>
                </Col>
            </Container>
        </>
    );
}

export default Product;

Upvotes: 3

ABHIJEET KHIRE
ABHIJEET KHIRE

Reputation: 2471

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
    };

   // if we are using arrow function binding is not required
   //  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;

Upvotes: 35

poeticGeek
poeticGeek

Reputation: 1041

using react-uploady you can do this very easily:

import React from "react";
import Uploady from "@rpldy/uploady";
import UploadButton from "@rpldy/upload-button";
import UploadPreview from "@rpldy/upload-preview";

const filterBySize = (file) => {
  //filter out images larger than 5MB
  return file.size <= 5242880;
};

const App = () => (
  <Uploady
    destination={{ url: "my-server.com/upload" }}
    fileFilter={filterBySize}
    accept="image/*"
  >
    <UploadButton />
    <UploadPreview />   
  </Uploady>
);

Upvotes: 0

Thananjaya S
Thananjaya S

Reputation: 1679

If you want to upload image and post it to an API. Then you install react-image-uploader. It saves the image to your local port and also in your database by raising a POST request.

Upvotes: 3

Related Questions