0

I'm trying to upload images using react js but I'm not able to upload multiple images at the same time even though I gave input as multiple.

<input type="file" title="" className={styles.inputFile} multiple={true} onChange={handleChange} />

 const [formData, setFormData] = useState({
    orgId: "6114285831310bfd5b09c28178e",
    orgWallpaper: [],
  }); 

const handleChange = (e) => {
    if (e.target.files && e.target.files[0]) {
      setFormData((form) => ({
        ...form,
        orgWallpaper: [...form.orgWallpaper, URL.createObjectURL(e.target.files[0])],
      }));
    }
  };

{formData?.orgWallpaper?.map((item, key) => (
                  {console.log(item, "mapitem")}
                  <img className={styles.wallpapers + " " + styles.active} src={item} alt="" />

2 Answers 2

1

You should change handleChange like below

const {useState} = React;

const MultipleFilesUpload = () => {
  const [formData, setFormData] = useState({
    orgId: "6114285831310bfd5b09c28178e",
    orgWallpaper: [],
  });

  const handleChange = (e) => {
    var files = e.target.files;
   for (let i = 0; i <files.length; i++) {
   setFormData((form) => ({
        ...form,
        orgWallpaper: [...form.orgWallpaper, URL.createObjectURL(files[i])]})
        )}};
        
  return ( 
  <div>
      <input type="file" title="" multiple onChange={handleChange}/> 
      <div class="gallery">
      {
      formData.orgWallpaper.map((item, key) =>
        <img width ="48px" src ={item} alt= "" />
      )} 
      </div> 
   </div>
)};

ReactDOM.render( <MultipleFilesUpload/> ,
  document.getElementById("root")
);
.gallery {
  display: flex;
}

.gallery img {
  margin: 10px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/17.0.1/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/17.0.1/umd/react-dom.production.min.js"></script>
<div id="root"></div>

Sign up to request clarification or add additional context in comments.

Comments

0

You may check this :

...(e.target.files?.map(file=>URL.createObjectURL(file))??[])

and also remove console log, its actually breaking the return syntax. If you want to check console.log then also write a return :

 {formData?.orgWallpaper?.map((item, key) => ( <img key={key} className={styles.wallpapers + " " + styles.active} src={item} alt="" />)
    }

4 Comments

Also please add key attribute in image markup as recommended by react
Hi, ty for reply.. do u mean i need to try like this ?orgWallpaper: [...form.orgWallpaper, ...(e.target.files?.map(file=>URL.createObjectURL(file))??[])],
Yes. Give it a try please
yeah i tried but it throwing empty array :(

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.