经验首页 前端设计 程序设计 Java相关 移动开发 数据库/运维 软件/图像 大数据/云计算 其他经验
当前位置:技术经验 » HTML/CSS » 浏览器 » 查看文章
使用JSZip实现在浏览器中操作文件与文件夹
来源:cnblogs  作者:当时明月在曾照彩云归  时间:2024/4/19 8:55:05  对本文有异议

1. 引言

浏览器中如何创建文件夹、写入文件呢?

答曰:可以借助JSZip这个库来实现在浏览器内存中创建文件与文件夹,最后只需下载这个.zip文件,就是最终得结果

类似的使用场景如下:

  • 在线下载很多图片,希望这些图片能分类保存到各个文件夹并最终下载成一个zip文件
  • 在线下载很多文档,希望这些文档能分类保存到各个文件夹并最终下载成一个zip文件

本质上都是希望浏览器能创建文件夹和创建文件,最终保存成一个文件来提供下载

JSZip的GitHub站点:Stuk/jszip: Create, read and edit .zip files with Javascript (github.com)

一个可用的中文站点:JSZip参考手册 (asprain.cn)

下面主要记录一下基础使用,详细的API请参考上述文档

2. 使用

2.1 安装

使用NPM:

  1. npm install jszip

使用在线CDN:

  1. <script src="https://cdn.bootcdn.net/ajax/libs/jszip/3.10.1/jszip.js"></script>
  • 为了可以代码可以快速复现,笔者这里使用CDN的方式引入

2.2 创建zip实例

一个JSZip实例是读写.zip文件的基础

  1. const zip = new JSZip();

2.3 读取zip文件

读取官方的示例文件text.zip

  1. const zip = new JSZip();
  2. fetch("https://stuk.github.io/jszip/test/ref/text.zip") // 1) fetch the url
  3. .then(function (response) { // 2) filter on 200 OK
  4. if (response.status === 200 || response.status === 0) {
  5. return Promise.resolve(response.blob());
  6. } else {
  7. return Promise.reject(new Error(response.statusText));
  8. }
  9. })
  10. .then(data => zip.loadAsync(data)) // 3) 加载数据
  11. .then(function (zip) {
  12. zip.forEach(function (relativePath, file) { // 4) 遍历压缩包内的文件
  13. console.log(`path: ${relativePath}, file: ${file.name}`)
  14. // 输出:path: Hello.txt, file: Hello.txt
  15. });
  16. })

因为Hello.txt是个文本文件,可以直接使用string的方式读取内部的数据

  1. const zip = new JSZip();
  2. fetch("https://stuk.github.io/jszip/test/ref/text.zip") // 1) fetch the url
  3. .then(function (response) { // 2) filter on 200 OK
  4. if (response.status === 200 || response.status === 0) {
  5. return Promise.resolve(response.blob());
  6. } else {
  7. return Promise.reject(new Error(response.statusText));
  8. }
  9. })
  10. .then(data => zip.loadAsync(data)) // 3) chain with the zip promise
  11. .then(function (zip) {
  12. return zip.file("Hello.txt").async("string"); // 4) 读取Hello.txt文件
  13. })
  14. .then(function success(text) {
  15. console.log(text); // 输出:Hello World
  16. }, function error(e) {
  17. console.error(e);
  18. });

2.4 创建zip文件

写入文件与数据

  1. zip.file("file.txt", "content");
  2. new Promise((resolve, reject) => {
  3. resolve(zip.file("file.txt").async("string"))
  4. }).then(data => {
  5. console.log(data); // 输出:content
  6. })

写入指定文件夹下的指定文件

  1. zip.file("text/file.txt", "content");
  2. zip.forEach(function (relativePath, file) {
  3. console.log(`path: ${relativePath}, file: ${file.name}`)
  4. // 输出:path: text/file.txt, file: text/file.txt
  5. });

最后的目录结构可以参考下图

2.5 下载zip文件

这里将上面的file.txt下载为zip,使用a链接的方式

  1. zip.generateAsync({ type: "blob" }).then(function (content) {
  2. document.body.appendChild(document.createElement("a"));
  3. document.querySelector("a").href = URL.createObjectURL(content);
  4. document.querySelector("a").download = "test.zip";
  5. document.querySelector("a").click();
  6. });

image

完整的代码如下:

  1. <!DOCTYPE html>
  2. <html lang="en">
  3. <head>
  4. <meta charset="UTF-8">
  5. <meta name="viewport" content="width=device-width, initial-scale=1.0">
  6. <title>Document</title>
  7. <script src="https://cdn.bootcdn.net/ajax/libs/jszip/3.10.1/jszip.js"></script>
  8. </head>
  9. <body>
  10. <script>
  11. const zip = new JSZip();
  12. // fetch("https://stuk.github.io/jszip/test/ref/text.zip") // 1) fetch the url
  13. // .then(function (response) { // 2) filter on 200 OK
  14. // if (response.status === 200 || response.status === 0) {
  15. // return Promise.resolve(response.blob());
  16. // } else {
  17. // return Promise.reject(new Error(response.statusText));
  18. // }
  19. // })
  20. // .then(data => zip.loadAsync(data)) // 3) chain with the zip promise
  21. // .then(function (zip) {
  22. // return zip.file("Hello.txt").async("string"); // 4) chain with the text content
  23. // })
  24. // .then(function success(text) {
  25. // console.log(text);
  26. // }, function error(e) {
  27. // console.error(e);
  28. // });
  29. zip.file("text/file.txt", "content");
  30. zip.forEach(function (relativePath, file) {
  31. console.log(`path: ${relativePath}, file: ${file.name}`)
  32. });
  33. zip.generateAsync({ type: "blob" }).then(function (content) {
  34. document.body.appendChild(document.createElement("a"));
  35. document.querySelector("a").href = URL.createObjectURL(content);
  36. document.querySelector("a").download = "test.zip";
  37. document.querySelector("a").click();
  38. });
  39. </script>
  40. </body>
  41. </html>

3. 参考资料

[1] How to use JSZip (stuk.github.io)

[2] JSZip参考手册 (asprain.cn)

原文链接:https://www.cnblogs.com/jiujiubashiyi/p/18144295

 友情链接:直通硅谷  点职佳  北美留学生论坛

本站QQ群:前端 618073944 | Java 606181507 | Python 626812652 | C/C++ 612253063 | 微信 634508462 | 苹果 692586424 | C#/.net 182808419 | PHP 305140648 | 运维 608723728

W3xue 的所有内容仅供测试,对任何法律问题及风险不承担任何责任。通过使用本站内容随之而来的风险与本站无关。
关于我们  |  意见建议  |  捐助我们  |  报错有奖  |  广告合作、友情链接(目前9元/月)请联系QQ:27243702 沸活量
皖ICP备17017327号-2 皖公网安备34020702000426号