51

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

6 Answers 6

83
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;
Sign up to request clarification or add additional context in comments.

4 Comments

This worked beautifully in my nextjs site, and I could insert it seamlessly without needing to worry about classes or render(), thank you so much and may all your programs compile on their first run
good job, but after removing the image, it stops working on my end
For making work after removing the image, you need to clear the file input as well.
You can use a ref and pass it to your input so you can clear the input ref value, and then it will work smoothly.
36

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;

2 Comments

you don't need this.onImageChange = this.onImageChange.bind(this); if you have a arrow function
check the updated code using react hook's check the link ==> stackoverflow.com/a/68979570/8621764
3

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.

Comments

3

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;

Comments

0

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

Comments

0

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]);

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.