Sometimes you need to read files which are in the user’s local machine. Here is where HTML File API comes into play. The use case I’m going to explain is when you want to make a preview of an image which has not been uploaded anywhere yet, so you don’t have the url of the image.
Also, if the file is TIFF or PDF the thing complicates. But the good news is that the preview is also possible. All the examples below make use of jQuery library. If you are interested how, continue reading.
Preview web standard images
Below is the usual way of reading files using File API to make a preview of a standard JPG or PNG image.
1 2 3
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
Note that first thing is to get the reference of the file/s on the change event. After that, we have to create an instance of FileReader to be able to read the file properly. Once we make sure that our browser supports FileReader and we have a reference to the file, then we read the file.
The outstanding aspect here is how we are reading the file with FileReader. Some methods are provided to read files. In this particular case we use FileReader.readAsDataURL(Blob|File) because the result property will contain the file/blob’s data encoded as a data URL and that’s what we are looking for in the
Preview TIFF images
Displaying a tiff image on the web has been always a nightmare. And still there’s no standard way of achieving it. For our example we’ll use seikichi’s tiff.js library.
Remember to add tiff js library.
Now, our fileTypes array will have support for tiff files only.
And, here is how we read and render tiff files.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32
The main difference here is now we are reading the file using FileReader.readAsArrayBuffer(Blob|File) and the image will be rendered on a HTML5 Canvas element.
Preview PDF files
Obviously, PDF files are not web compliant, so we have to make use of external libraries which help us deal with these type of files. A very well-known is the Mozilla PDF JS library. In our example we are going do a preview of the first page of the pdf file.
First, remember to include pdf js library in your html. You have to follow the steps described in the documentation to build the pdf.js project and generate the necessary pdf.js and pdf.worker.js files.
Now, our fileTypes array will have support for pdf files.
Below is how we read the first page of a pdf file and render it on a HTML5 Canvas element.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43
You can view or download the full example on this plunker