10 april 2024

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).

PDF

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:


If you noticed a typo, or have a correction or question — write a comment to [email protected]