简体   繁体   中英

React JS: Upload Multiple Files

I am writing a button component in React.js that allows the user to upload as many files as they want to the app. My problem is, I can only upload one file at a time with the following code:

  const handleClick = event => {
    setViewPath(['My Files']);
    hiddenFileInput.current.click();
  };
  // Call a function (passed as a prop from the parent component)
  // to handle the user-selected file
  const handleChange = event => {
    const fileUploaded = event.target.files[2];
    props.handleFile(fileUploaded);
  };
  return (
    <>
      <Button className={classes.uploadButton}
      onClick={handleClick}>
        +Upload File(s)
      </Button>
      <input
        type="file"
        ref={hiddenFileInput}
        onChange={handleChange}
        style={{display: 'none'}}
      />
    </>
  );

So the function "const handleChange" is what's responsible for uploading the actual file itself. Any ideas on how to make it so that it can upload as many files as the user pleases?

You need to add multiple attribute to your input field.

<input type="file" id="files" name="files" multiple>

Your files state should be an array and handleChange should be something like this.

const handleChange = e => {    
setData({
        ...data,
        files: [...data.files, ...e.target.files],
      });
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM