Hi, how do I rename the files that I have just dropped ?
My use case, if I upload a file, and upload another one with the same name as previous one, it will override the previous file. So to encounter that, I should append some uniqueness to the filename. How do I achieve this ?
Thank you.
@nzwnabdulwahid you can override on the onDrop method w/ your own method that has the logic to handle this. Similar to what I have done on another component wrapping dropzone
onDrop(acceptedFiles, rejectedFiles) {
const accepted = this.state.acceptedFiles.slice(0);
let error = null;
acceptedFiles.forEach((file) => {
const exists = accepted.some(f => f.name === file.name && f.size === file.size);
if (!exists) {
accepted.push(file);
} else {
error = this.props.duplicateError;
}
});
if (rejectedFiles.some((file) => file.size > this.props.maxSize)) {
error = this.props.maxSizeError;
} else if (rejectedFiles.some((file) => file.type !== this.props.accept)) {
error = this.props.acceptTypeError;
}
this.props.onChange(accepted);
this.setState({
acceptedFiles: accepted,
error: error
});
}
In this manner I am allowing my component to handle an array of uploads to attach to the state of the component. also since this isn't really an issue I am going to close this but feel free to add comments if you need more help :)
Apologies for commenting on this old really issue.
To save anyone else a few more google searches, the quick answer is to clone the File object passing in a new name :+1:
onDrop(acceptedFiles, rejectedFiles) {
...
const renamedAcceptedFiles = acceptedFiles.map((file) => (
new File([file], `${file.name}_${+new Date()}`, { type: file.type })
))
...
}
@jimleuk
This wouldn't work on IE & Edge plus Opera for Android
because they can handle File, but not the File() constructor.
https://stackoverflow.com/a/50011806
https://developer.mozilla.org/en-US/docs/Web/API/File/File
@jimleuk How do you pluck the extension from the original filename and tag it onto the new name? (besides split etc.)
Most helpful comment
Apologies for commenting on this old really issue.
To save anyone else a few more google searches, the quick answer is to clone the
Fileobject passing in a new name :+1: