DEV Community

Uploading PDF files as base64 strings in PHP and saving it in the hard-disk.

Rogerio Taques on February 14, 2020

Hi there! If you’re reading this post, chances are you’re having some issues when trying to upload (PDF) files as base64 strings to later store th...
Collapse
 
jsardev profile image
Jakub Sarnowski • Edited

Isn't it a lot easier to upload files using multipart/form-data? I think that using base64 is a lot of unnecessary logic.

Collapse
 
rogeriotaques profile image
Rogerio Taques

Yo! Thanks for your comment. 🙇‍♂️

I think it heavily depends on the architecture of your app.

In our case here, the app doesn't really have a form in the first place, so all the data is gathered from the component state and sent as a JSON to the API, therefore we're not actually submitting a form.

Also, on the backend, files are not stored in the hard-disk but in the database as base64 strings alongside many other meta-information which are used later on.

Collapse
 
jsardev profile image
Jakub Sarnowski

You don't need a form to accept multipart data. It's a common pattern to use it in API's.

Also, storing files as base64 strings in a database is a bad idea as again you have this unnecessary encoding/decoding overhead. Why not just store the data as binary data blobs?

I just think that using base64 for that is just a performance waste for your API and your API clients.

Thread Thread
 
rogeriotaques profile image
Rogerio Taques

Sounds like a point! 🙂Tbh, I couldn't find a consensus about what would be the best-practice for that, so I'm curious about how would you do it. Would you mind to give me an example?

Thread Thread
 
jsardev profile image
Jakub Sarnowski

I took example from the Google Drive API. You can easily send files + metadata (even as JSON!) without any encoding/decoding and you have binary data right in your API.

According to storing files in database as base64 strings, take a look here.

What do you think about that? 😃 I think you can gain a lot of performance this way.

Thread Thread
 
rogeriotaques profile image
Rogerio Taques

Interesting, man!

Not really sure about the real benefit of not using base64 as a transport wrapper when posting data to the API (in my particular scenario) , but I’m definitely convinced of the advantages of storing the binary instead.

Thanks a lot for the contribution. 🙌 I’ll take the opportunity with a new project here and try this approach out.

Thread Thread
 
jsardev profile image
Jakub Sarnowski

Yeah I don't mean that your approach is wrong, it will surely work! I just wanted to propose a better approach 😃

Thread Thread
 
rogeriotaques profile image
Rogerio Taques

Sure, I didn’t take it wrong! 😉 It’s awesome have the chance to see what other devs would do to solve situations we’ve faced before. 🤘 Really glad you’ve commented.