客户端保存文件组件FileSaver.js的简单使用

FileSaver.js 是在客户端保存文件的解决方案,非常适合需要生成文件

语法:

FileSaver saveAs(Blob/File data, optional DOMString filename, optional Boolean disableAutoBOM)

 示例:

<canvas id="example" width="600" height="300" style="border: solid 1px #ccc"></canvas>
<script src="./plugins/FileSaver.js"></script>
<script>
  // 保存文本
  saveAs(
    new Blob([JSON.stringify({ aa: 1 })], {
      type: "text/plain;charset=utf-8",
    }),
    "file.txt"
  );
  saveAs(
    new Blob(["Hello, world!"], {
      type: "text/plain;charset=utf-8",
    }),
    "file2.txt"
  );

  //保存画布
  var canvas = document.getElementById("example");
  const context = canvas.getContext("2d");
  context.moveTo(0, 0);
  context.lineTo(100, 0);
  context.lineTo(100, 100);
  context.lineTo(0, 100);
  context.lineTo(0, 0);
  context.stroke();
  canvas.toBlob(function (blob) {
    saveAs(blob, "img.png");
  });

  //保存文件
  var file = new File(["Hello, world222!"], { type: "text/plain;charset=utf-8" });
  saveAs(file, "file3.txt");
</script>

 

posted @ 2023-03-22 11:26  carol2014  阅读(438)  评论(0编辑  收藏  举报