0

I am using the FileReader() API to read files on the browser, I want to render something on the screen conditionally based on the file the user uploads:

  • JSON.
  • CSV.
  • Excel.

How can I detect if the file uploaded is an excel file? Do you use libraries for that or is there a genius way we can detect that blindly without going through all the chances?

Normal
  • 1,616
  • 15
  • 39
  • btw I'm working with react, so I can use npm – Normal Sep 12 '22 at 21:12
  • 1
    Check if it isn't a JSON file and if it isn't a CSV file. – kelsny Sep 12 '22 at 21:13
  • Generally one relies on the file extension. `.xlsx' would be Excel – Codebling Sep 12 '22 at 21:14
  • 1
    Alternatively you can just try to parse the files as each type and if it fails you know it isn't of that type – Codebling Sep 12 '22 at 21:14
  • @Codebling, okay good solutions, thanks. btw, you can't rely on the file extension, because if the user is on Linux he can store his files without an extension on his computer – Normal Sep 12 '22 at 21:15
  • You can also store your files without an extension on Windows. It's just common to keep the extensions, on both linux and Windows (source: I am a linux user). – Codebling Sep 12 '22 at 22:09
  • If you don't have an extension on linux, the OS doesn't know what type the file is. You can manually run `file` command to detect the file type – Codebling Sep 12 '22 at 22:14
  • @Normal Linux uses file extensions. Some file browsers will hide them. Double-check the actual filename with `ls` and you'll probably see they have extensions. – Christian Stewart Sep 12 '22 at 23:54

1 Answers1

1

Running out of space in comments, so I'll add an answer. Files will usually have an extension, on both Windows and Linux, but if you don't want to rely on that you can just try parsing the file in each of the formats to find the one that succeeds.

Codebling
  • 10,764
  • 2
  • 38
  • 66