How to preview files in browser
Recently I was building an in-browser document preview, and it appeared to be a quirky task because browsers usually assume that users handle opening files on their machine.
This is what I found out:
- images — just use
<img/>
tag - csv — it’s trivial to parse csv in the browser, as you need to just split the file into rows by
\n
and then split them into columns by a separator (which can be,
,;
,space
etc). As separators introduce some caveats, I recommend using some readymade solutions like papaparse’sPapa.parse(csvAsString)
. - pdf — browsers can open these with
<embed src="example.pdf"/>
. - For office documents like ppt, pptx, doc, docx, xls, and xlsx — there are two types of solutions:
- you may use some quirky library made by some unknown geniuses (example), but as proprietary formats are complicated results may vary
- you may use iframe from «format owners» like Microsoft and Google. There is a nice gist about these on github. In my experience Google iframe is very unreliable, so don’t be tempted to use it because of a huge variety of formats — just go with Microsoft’s one. Of course, if you are going with this option, you must keep in mind the privacy part of sending documents to someone’s API.