Handling files in the browser
With the introduction of the new
File API in most modern browsers, it is now incredibly easy to deal with data in the browser compared to in the past. This combined with the typed arrays, such as
Uint8Array, allows us to quite easily read and manipulate raw data.
The most common use case for wanting to read a file is that of file uploads. With the
File API we can now read a user selected file in any way we want and even output a modified version of it.
Here’s an example:
This is fairly simple, we get the
this.files and use a
FileReader to read it into an
ArrayBuffer. Finally, we log the buffer to console, though we will need to use something like an
Int8Array to actually output the data.
Of course, some extra code will be needed when handling large files this way to avoid loading too much into memory at any one time.
Canary has recently been updated with the addition of a
File constructor, so you can now create files inside the browser.
Here, the first parameter is an array of parts just as with the
Blob constructor. The second and third define the name and any additional options respectively (such as content type).
This will result in a
File instance which can then be read and manipulated like any other. You may pass it to a
FileReader or post it to be uploaded to a remote server, so the possibilities are endless.
I definitely suggest you go check out the entire File API. You could quite easily write a parser of some sort or even something to manipulate files which the user can then download.