How to preview files in browser
Recently I was building an in-browser document preview. It turned out to be a quirky task because browsers usually assume that users handle opening files on their own machine.
This is what I found out:
Images
That one is obvious — just use the <img/> tag
CSV
It’s trivial to parse CSV in the browser — you just split the file into rows by \n and then split them into columns by a separator (which can be ,, ;, space, etc.).
Since separators introduce some caveats, I recommend using readymade solutions like papaparse’s Papa.parse(csvAsString).
Browsers can preview PDFs with <embed src="example.pdf"/>.
Sadly, mobile Safari can’t, so if this is crucial for you, you might need to use one of the many libraries for that. In my experience, such libraries have tons of glitches — keep that in mind.
Office documents
For office documents like ppt, pptx, doc, docx, xls, and xlsx, there are two types of solutions:
-
You can use some quirky library made by unknown geniuses (example), but since proprietary formats are complicated, results may vary
-
You can use an iframe from “format owners” like Microsoft and Google. There is a nice gist about these on GitHub. In my experience, Google’s iframe is very unreliable, so don’t be tempted to use it because of the huge variety of formats — just go with Microsoft’s one. Of course, if you go with this option, you must keep in mind the privacy implications of sending documents to someone’s API.