Friday 27 November 2020

How to increment the filename if file already exists in javascript

I have implemented Drag and Drop File Upload in my react project, so on every drag and drop of file into the drop zone , I'm taking the file and accessing it's name and it's data and converting the data to base64 using javscript's FileReader() and readAsDataURL() and updating the state, which I need to send it to bakend.

How to append a number to filename if the file with same name already exist in the state ?

eg: file(1).csv or file 2.csv

enter image description here

Main State

this.state : {
     Files:[],
}

Function that get's triggered every time for drag and drop of file

   FileHandling = (files) => {
    files.forEach((file) => {
      const reader = new FileReader();

      reader.readAsDataURL(file);
      reader.onload = () => {

        const CompleteData= {
          fileData: reader.result,
          fileName: file.name,
        };
         this.setState({
             Files:[...this.state.Files, CompleteData]
            })
      };
    });
  };


from How to increment the filename if file already exists in javascript

No comments:

Post a Comment