Skip to content
Advertisement

How to read a csv file from input element with vanilla js?

I’ve been trying to read a csv file provided by the user with html form and then process the data. I wanted to approach this with Fetch. It works great when reading a file located on a server.

JavaScript

Problem starts when I want to let the user pick a local file.

JavaScript
JavaScript

Of course it doesn’t work as it takes correct file name but thinks it’s on the server. I have tried it many other ways but got fakepath, object element, CORS and other issues.

I have also tried to approach the problem with FileReader, got the data but faced promiseless async problems and couldn’t await for the data to put them outside in a variable.

What’s the best approach? Is it possible to solve the problem with vanilla js without uploading the file to the server? I thought this should be super easy, even for an absolute beginner like me but I wasted so much time and thought to ask you for help. Maybe there’s something else that I’m doing wrong. Thank you for help.

Advertisement

Answer

Here’s how you’d do this, adapted from this question.

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