Jamie
Jamie

Reputation: 2291

How to extract a zip file and render the contents, client side

I have a zip file located at http://my-website.com/user-site.zip. This zip file contains a bunch of html, css and javascript files that, when extracted, look something like this (exact contents unknown):

index.html
js/
  script.js
css/
  style.css

I want to be able to view this webpage in, e.g., an iframe, after downloading it in-browser.

Right now my approach looks like this:

  1. Download the zip file from the server.
  2. Use zip.js to extract the files in-memory.
  3. Use createObjectUrl (explained here) to create urls for each of these assets.
  4. Point the iframe to the url generated by index.html.

This almost works, except for one problem. The urls generated by createObjectUrl are pretty much random, so index.html can't resolve references to other resources. How can I get around this?

Upvotes: 10

Views: 7259

Answers (1)

RickyAYoder
RickyAYoder

Reputation: 991

Very great question! I'm sitting here pondering this myself now! One thing that you could do is create a JavaScript object/array to "map" the files and their paths, along with their created object URLs. Then use JavaScript to replace the relative paths with the absolute object URLs. Unless...you can't get the path of the file.

If that is the case, a JavaScript library you may be interested in would be JSZip, which can give you paths for files within a ZIP.

JSZip Example

For your map, you could do something like this (after you strip necessary parts from the JSZip path like the root directory):

var map = [
    {"relativePath":"css.css","absolutePath":*Object URL Goes Here*}
];

Then loop through each entry in the map and replace every instance of relativePath[x] with the absolutePath[x] in a given file, whether it be the raw text of the file or the innerHTML of the iframe.

Hope this helps!

Upvotes: 3

Related Questions