2

I have currently implemented uploading a single file to my react app, but want to upload multiple files, below is the code I am using to upload a single file. Is it possible to upload multiple files?

 captureFile = (event) => {
    const file = event.target.files[0]
    const reader = new window.FileReader()
    reader.readAsArrayBuffer(file)
    reader.onloadend = () => {
      this.setState({
        buffer: Buffer(reader.result),
        file: URL.createObjectURL(file),
      })
    }
  }

This is what I am trying to do at the moment

  captureFile = (event) => {
    const files = event.target.files
    for (let i = 0; i < files.length; i++) {
      const file = files[i]
      const reader = new window.FileReader()
      reader.readAsArrayBuffer(file)

    reader.onloadend = () => {
      this.setState({
        buffer: Buffer(reader.result),
        file: URL.createObjectURL(file),
      })
    }
  }
4
  • What have you tried so far in order to handle multiple files? Commented May 17, 2019 at 2:53
  • Edited as above Commented May 17, 2019 at 8:25
  • you can use multiple prop if you are using default input Commented May 17, 2019 at 15:25
  • Hi @sumanth, thank you for your help, what would the best way to do that be? Commented May 18, 2019 at 3:23

1 Answer 1

2

You can use FileReader or UrlObject for read images or files like this:

    const[selectedFiles,setSelectedFiles] = useState([]);

    captureFile = (event) => {
    let files = [];
    for (let file of event.target.files) {
      files.push(URL.createObjectURL(file));
      }
    setSelectedFiles(files);
   }

then you can iterate over selectedFiles by map function like:

   selectedFiles.map((item,key) => (<img key={key} src={item} />));

It works for me instead of FileReader because it uses callback functions.

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

Comments

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.