Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

211
Vistas
How to display the selected image in reactjs

I wanted to upload images and display the image which was chosen, How to display the image after choosing. this is my code, help me display the image, I made the function to post the image, I can post multiple images in one click but i can't display the image to preview before upload , i try to use file reader but cannot display and upload.

   
  const [pImg, setPImg] = useState([]);
  const [images, setImages] = useState([]);

 
  const addImg = (ImagesPostDto) => {
    const data2 = new FormData();
    [...ImagesPostDto].forEach((Images) => {
      data2.append("ImagesPostDto", Images);
    });
    Axios.post(`/shop/${shopID}/Product/${pID}/Images`, data2)
      .then((res) => {
        if (res.status === 200) {
          setMessage({
            data: `${res.data.MESSAGE}`,
            type: "alert-success",
          });
          onShowAlert();
        }
      })
      .catch((err) => {
        setMessage({
          data: `${err.response.data.MESSAGE}`,
          type: "alert-danger",
        });
        setLoading(false);
        onShowAlert();
      });
  };

  const handleImageChange = (e) => {
    e.preventDefault();
    const ProductImg = e.target.files;
    setPImg(ProductImg);
const reader = new FileReader();

reader.onloadend = () => {
  setPImg(ProductImg);
  setImages(reader.result);
};
reader.readAsDataURL(ProductImg);
  };

  const handleProductSubmit = (event) => {
    event.preventDefault();
    addImg(pImg);
  };
  
  return (
    <div>
      
   
        <Form>
          <p>
            <Label htmlFor="file">Upload images</Label>
            <input
              type="file"
              id="file"
              onChange={handleImageChange}
              accept="image/png, image/jpg, image/jpeg"
              multiple
            />
          </p>
        </Form>
        <div className="">
          {/* {images.length > 0 ? (
            <div>
              {images.map((image) => (
                <p>
                  <img src={images} alt="" />
                </p>
              ))}
            </div>
          ) : null} */}
        </div>
      

about 4 years ago · Santiago Gelvez
3 Respuestas
Responde la pregunta

0

If you want to render images then, create ObjectURL from files array and set the images State then it should work fine. I have commented the code related to API call so that we can focus on rendering the selected images.You can just simply copy this code and paste it in CodeSandBox it should work fine Here is your code a bit modified:

import "./styles.css";
import { useState } from "react";

export default function App() {
  const [pImg, setPImg] = useState([]);
  const [images, setImages] = useState([]);

  // const addImg = (ImagesPostDto) => {
  //   const data2 = new FormData();
  //   [...ImagesPostDto].forEach((Images) => {
  //     data2.append("ImagesPostDto", Images);
  //   });
  //   Axios.post(`/shop/${shopID}/Product/${pID}/Images`, data2)
  //     .then((res) => {
  //       if (res.status === 200) {
  //         setMessage({
  //           data: `${res.data.MESSAGE}`,
  //           type: "alert-success"
  //         });
  //         onShowAlert();
  //       }
  //     })
  //     .catch((err) => {
  //       setMessage({
  //         data: `${err.response.data.MESSAGE}`,
  //         type: "alert-danger"
  //       });
  //       setLoading(false);
  //       onShowAlert();
  //     });
  // };

  const handleImageChange = (e) => {
    e.preventDefault();
    console.log("event", e);
    const ProductImg = [...e.target.files];
    const images = ProductImg.map((image) => URL.createObjectURL(image));
    console.log("images", images);
    setImages(images);
  };

  // const handleProductSubmit = (event) => {
  //   event.preventDefault();
  //   addImg(pImg);
  // };

  return (
    <div>
      <form>
        <p>
          <label htmlFor="file">Upload images</label>
          <input
            type="file"
            id="file"
            onChange={handleImageChange}
            accept="image/png, image/jpg, image/jpeg"
            multiple
          />
        </p>
      </form>
      <div className="">
        {images.length > 0 && (
          <div>
            {images.map((image, index) => (
              <p key={index}>
                <img src={image} alt="" />
              </p>
            ))}
          </div>
        )}
      </div>
    </div>
  );
}

about 4 years ago · Santiago Gelvez Denunciar

0

You need to fetch the Images from GET API and set the response in setImages than it will show right now the images variable is empty array.

about 4 years ago · Santiago Gelvez Denunciar

0

As far I can understand your requirement, you need to preview the Images Either when you have selected or After uploaded.

What you can do is, whenever you are preparing the FormData or at the time of change event, you can store each selected file's ObjectURL in another state and Easily can display these images via the State.

about 4 years ago · Santiago Gelvez Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda