0

So in my backend (express and mongodb) I have a field inside of post model called picture and it's type is string. So in the frontend (React) I want the user to be able to select a file and then the file will be converted to a string then sent to the backend. I do not know how to do this nor have I been able to find any tutorial or blog on this. Thanks in advance!

  • Does this answer your question? [How to convert file to base64 in JavaScript?](https://stackoverflow.com/questions/36280818/how-to-convert-file-to-base64-in-javascript) – Alexey Kureev Jun 13 '22 at 15:54

2 Answers2

0

Google "convert file to string js". Then you need to do a POST request by putting that string to the BODY in your POST request but of course you need to handle this operation in your backend in one of your endpoints.

frankie303
  • 82
  • 7
  • But how will I even open a file picker? –  Jun 13 '22 at 07:41
  • you can check this: https://stackoverflow.com/questions/37457128/react-open-file-browser-on-click-a-div – frankie303 Jun 13 '22 at 07:48
  • When i search ```convert file to string js``` it tells me to use ```JSON.stringify(myObj)``` but what do I replace the ```myObj``` with? Please explain. Because if I replace it with ```inputFile.current.files[0]``` it just gives me an empty string –  Jun 13 '22 at 10:48
0

The functionality you are looking for is called FileReader API.

You might take a look at a very similar question here: How to convert file to base64 in JavaScript?.

Alexey Kureev
  • 1,978
  • 15
  • 25