Analysing files in PHP is easy. But what if you want to access the content of a file without the overhead of sending it to a server first (e.g. for displaying a thumbnail before uploading an image)?
Here’s the basic layout for this project. Don’t judge me for the design, as usual this post is mainly about functionality – you’re free to add all the bells and whistles you like!
When you open this page in your browser, you’ll see a heading and a non-functional button. Let’s change the latter!
The first part makes clicking the button open your browser’s file-dialog, while the second one calls a function
readFile. Curious about what this does? Check it out:
readFile has two arguments: a file from the file-input and a callback function. In it we first get a FileReader instance and tell it to call our callback with the result once it finished loading the file. Lastly we check the file-type to only process those we can process and read the file as text.
The callback function in this case is
It gets the text-content of the file and simply puts it into the
As if getting plain text from files wasn’t exciting enough, we’re can even go a step further and load an entire image!
To prepare for that, we first extend our layout:
We added another button as well as another result container. Ready for some more event listeners? Here they come!
readFile again. To also handle image files, we need to add a condition:
readAsDataURL returns the base64 encoded representation of the file content. The already existing
onload listener passes this data to the
displayImage callback for further processing:
With the encoded data we create a new image and add it to the
This has been a basic introduction to the FileReader-API. Feel free to play around with it! You can download the full script (right click and save as) to play around with it. Let me know in the comments what you ended up creating with this cool feature!