Skip to content
Advertisement

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

JavaScript

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

JavaScript

Advertisement

Answer

You can check this.state.Files before. A recursive function could be used here. Imagine you load a file named export.csv. The second one would export.csv transformed in export_1.csv. But on a third one named export.csv, the verification would be done on export, leading to export_1 => Error ! The best is to do :

JavaScript
User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement