Suman
Suman

Reputation: 93

How to add multiple files uisng reactjs

Here i'm trying to add multiple files to upload, but it is replacing in to new one and the response value is also showing empty. i dont understand what i'm doing wrong here thanks in advance

const [question, setQuestion] = React.useState('');
const [fileImage, setFileImage] = React.useState([]);

const handleChange = (event) => {
 setQuestion(event.target.value);
}

const handleSelectChange = (event) => {
 setFileImage(event.target.files);
}

addQuizDetails() {
  const Questions = question;
  const fileImages = fileImage;
  const headers = {
    "Content-Type": "multipart/form-data"
  }
  var formData = new FormData();
    formData.append("image", fileImages);
    formData.append("question",question )
    axios
    .post("http://localhost:4000/api/quiz/addQuiz",formData,headers)
    .then(response => {
      if (response.data.message) {
        alert(response.data.message)
      }
      else {
        alert("failed")
      }
  })
 }
}


 <TextField className={classes.content} onChange={handleChange} label="Question" variant="outlined" />
          <input 
            type="file" 
            onChange={handleSelectChange}
            multiple />
          <div className={classes.button}>
            <Button className={classes.submit} variant="contained" onClick={addQuizDetails}>Submit</Button>           
          </div>

Upvotes: 2

Views: 29

Answers (1)

Rashed Rahat
Rashed Rahat

Reputation: 2479

Try below code by using spread operator for array:

const handleSelectChange = (event) => {
    const selectedFiles = event.target.files
    setFileImage([...fileImage, ...selectedFiles]);
}

Upvotes: 1

Related Questions