简体   繁体   中英

Create and download (html/css/js) files client-side

I've built a code playground (similar to liveweave) using react. the users can save their "code playgrounds" and access them later. (using firebase db),this "code playgrounds"are just made of HTML, CSS, and js. I´m trying to add a functionality which allow the user to download a playground, the idea is that it will generate 3 separate files (one for each language in the playground)

1) is there a way to generate (HTML CSS and js) files and populate them with content client-side?

2) if so, would there be any chance to group those files inside a.rar also client-side?

3) if generating these files client-side is not the optimal solution/not possible, how would you approach this problem?

I was thinking maybe in an express server that queries the data from the db and then response with those files, but I would like to try a client-sided solution

Finally decided to use fileSaver.js package

import { saveAs } from "file-saver";
const saveFiles = () => {
    var blob = new Blob([makeHtml(getDocumentCode())], {
      type: "text/plain;charset=utf-8",
    });
    saveAs(blob, `${getFileName()}.html`);
  };

first, you need to make a blob out of the content of the file, in this case, it was HTML +css +js code, makeHtml function handles how the HTML document is constructed, then just pass that blob to the saveAs function along the name and extension for the file, then you can use saveFiles in response to any event like onClick

<button onClick={saveFile}>Download<button/>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM