简体   繁体   English

在客户端创建和下载 (html/css/js) 文件

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

I've built a code playground (similar to liveweave) using react.我已经使用 React 构建了一个代码游乐场(类似于 liveweave)。 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. (使用 firebase db),这个“代码游乐场”仅由 HTML、CSS 和 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)我试图添加一个允许用户下载 playground 的功能,这个想法是它将生成 3 个单独的文件(一个用于 playground 中的每种语言)

1) is there a way to generate (HTML CSS and js) files and populate them with content client-side? 1)有没有办法生成(HTML CSS 和 js)文件并在客户端填充内容?

2) if so, would there be any chance to group those files inside a.rar also client-side? 2) 如果是这样,是否有机会在客户端也将 a.rar 中的这些文件分组?

3) if generating these files client-side is not the optimal solution/not possible, how would you approach this problem? 3)如果在客户端生成这些文件不是最佳解决方案/不可能,您将如何解决这个问题?

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最后决定使用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首先,您需要从文件的内容中创建一个 blob,在本例中,它是 HTML +css +js 代码, makeHtml function 处理 HTML 文档的构建方式,然后将该 blob 传递给 saveAs function文件的名称和扩展名,那么您可以使用saveFiles来响应任何事件,例如 onClick

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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