最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How to extract a zip file and render the contents, client side - Stack Overflow

programmeradmin1浏览0评论

I have a zip file located at .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?

I have a zip file located at http://my-website./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?

Share Improve this question edited Dec 8, 2014 at 22:23 Jamie asked Dec 4, 2014 at 22:03 JamieJamie 2,3011 gold badge22 silver badges38 bronze badges
Add a ment  | 

1 Answer 1

Reset to default 3

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.

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!

发布评论

评论列表(0)

  1. 暂无评论