React-dropzone: Rename file onDrop

Created on 14 Mar 2018  路  4Comments  路  Source: react-dropzone/react-dropzone

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.

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 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 })
  ))
  ...
}

All 4 comments

@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.)

Was this page helpful?
0 / 5 - 0 ratings

Related issues

xswordsx picture xswordsx  路  3Comments

timothyallan picture timothyallan  路  4Comments

steverecio picture steverecio  路  4Comments

christiantigre picture christiantigre  路  4Comments

cbougatsa picture cbougatsa  路  3Comments