Keeping existing attachments when selecting additional files


Topic: Keeping existing attachments when selecting additional files

Mia Laurent asked 4 weeks ago

A user selects one document, then adds another batch. The upload field replaces the previous selection and retains one file.

Is there a supported way to append selections?


Mateusz Lazaru staff answered 4 weeks ago

Selecting files in a native file input does not by itself create an accumulating upload queue. If your application owns that queue, store the selected files in component state and merge each incoming batch using a functional state update. Do not assign a filename string to the file input's value.

Before adding that merge, please show which MDB upload component you use and what its callback returns after the second selection. Some callbacks expose the complete queue rather than just the new batch; merging that result blindly would create duplicates. Include your files state update and removal handler so we can suggest the correct approach.

https://react.dev/reference/react-dom/components/input


Mia Laurent commented 4 weeks ago

I reduced it to the native input inside our upload wrapper. The callback contains only the new selection: first proposal.pdf, then diagram.png. My setter replaces the list each time. We want selecting the same document again to leave just one copy in the queue.

const [files, setFiles] = useState([]);
function addFiles(event) {
  const selected = Array.from(event.target.files || []);
  setFiles(selected);
}
return <input type="file" multiple onChange={addFiles} />;

Mateusz Lazaru staff commented 3 weeks ago

Because this callback contains only the new batch, merge it with the current queue instead of replacing the queue. A functional update reads the latest state. The key below treats matching names, sizes and modification times as the same attachment.

Resetting the native input afterward allows selecting the same file again while the queue remains in React state. Your removal handler should update that same queue; the input's current selection is not the accumulated list.

const fileKey = file => ${file.name}:${file.size}:${file.lastModified};
function addFiles(event) {
  const selected = Array.from(event.target.files || []);
  setFiles(current => {
    const unique = new Map(current.map(file => [fileKey(file), file]));
    selected.forEach(file => unique.set(fileKey(file), file));
    return [...unique.values()];
  });
  event.target.value = '';
}

Please insert min. 20 characters.

FREE CONSULTATION

Hire our experts to build a dedicated project. We'll analyze your business requirements, for free.

Status

Answered

Specification of the issue
  • User: Free
  • Premium support: No
  • Technology: MDB React
  • MDB Version: MDB5 9.0.0
  • Device: Laptop
  • Browser: Chrome
  • OS: Windows 11
  • Provided sample code: No
  • Provided link: No