詳解如何使用JSZip實(shí)現(xiàn)在瀏覽器中操作文件與文件夾
1. 引言
瀏覽器中如何創(chuàng)建文件夾、寫(xiě)入文件呢?
答曰:可以借助JSZip這個(gè)庫(kù)來(lái)實(shí)現(xiàn)在瀏覽器內(nèi)存中創(chuàng)建文件與文件夾,最后只需下載這個(gè).zip文件,就是最終得結(jié)果
類(lèi)似的使用場(chǎng)景如下:
- 在線下載很多圖片,希望這些圖片能分類(lèi)保存到各個(gè)文件夾并最終下載成一個(gè)zip文件
- 在線下載很多文檔,希望這些文檔能分類(lèi)保存到各個(gè)文件夾并最終下載成一個(gè)zip文件
本質(zhì)上都是希望瀏覽器能創(chuàng)建文件夾和創(chuàng)建文件,最終保存成一個(gè)文件來(lái)提供下載
JSZip的GitHub站點(diǎn):Stuk/jszip: Create, read and edit .zip files with Javascript (github.com)
一個(gè)可用的中文站點(diǎn):JSZip參考手冊(cè) (asprain.cn)
下面主要記錄一下基礎(chǔ)使用,詳細(xì)的API請(qǐng)參考上述文檔
2. 使用
2.1 安裝
使用NPM:
npm install jszip
使用在線CDN:
<script src="https://cdn.bootcdn.net/ajax/libs/jszip/3.10.1/jszip.js"></script>
為了可以代碼可以快速?gòu)?fù)現(xiàn),筆者這里使用CDN的方式引入
2.2 創(chuàng)建zip實(shí)例
一個(gè)JSZip實(shí)例是讀寫(xiě).zip文件的基礎(chǔ)
const zip = new JSZip();
2.3 讀取zip文件
讀取官方的示例文件text.zip
const zip = new JSZip(); fetch("https://stuk.github.io/jszip/test/ref/text.zip") // 1) fetch the url .then(function (response) { // 2) filter on 200 OK if (response.status === 200 || response.status === 0) { return Promise.resolve(response.blob()); } else { return Promise.reject(new Error(response.statusText)); } }) .then(data => zip.loadAsync(data)) // 3) 加載數(shù)據(jù) .then(function (zip) { zip.forEach(function (relativePath, file) { // 4) 遍歷壓縮包內(nèi)的文件 console.log(`path: ${relativePath}, file: ${file.name}`) // 輸出:path: Hello.txt, file: Hello.txt }); })
因?yàn)?code>Hello.txt是個(gè)文本文件,可以直接使用string
的方式讀取內(nèi)部的數(shù)據(jù)
const zip = new JSZip(); fetch("https://stuk.github.io/jszip/test/ref/text.zip") // 1) fetch the url .then(function (response) { // 2) filter on 200 OK if (response.status === 200 || response.status === 0) { return Promise.resolve(response.blob()); } else { return Promise.reject(new Error(response.statusText)); } }) .then(data => zip.loadAsync(data)) // 3) chain with the zip promise .then(function (zip) { return zip.file("Hello.txt").async("string"); // 4) 讀取Hello.txt文件 }) .then(function success(text) { console.log(text); // 輸出:Hello World }, function error(e) { console.error(e); });
2.4 創(chuàng)建zip文件
寫(xiě)入文件與數(shù)據(jù)
zip.file("file.txt", "content"); new Promise((resolve, reject) => { resolve(zip.file("file.txt").async("string")) }).then(data => { console.log(data); // 輸出:content })
寫(xiě)入指定文件夾下的指定文件
zip.file("text/file.txt", "content"); zip.forEach(function (relativePath, file) { console.log(`path: ${relativePath}, file: ${file.name}`) // 輸出:path: text/file.txt, file: text/file.txt });
最后的目錄結(jié)構(gòu)可以參考下圖
2.5 下載zip文件
這里將上面的file.txt下載為zip,使用a鏈接的方式
zip.generateAsync({ type: "blob" }).then(function (content) { document.body.appendChild(document.createElement("a")); document.querySelector("a").href = URL.createObjectURL(content); document.querySelector("a").download = "test.zip"; document.querySelector("a").click(); });
完整的代碼如下:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> <script src="https://cdn.bootcdn.net/ajax/libs/jszip/3.10.1/jszip.js"></script> </head> <body> <script> const zip = new JSZip(); // fetch("https://stuk.github.io/jszip/test/ref/text.zip") // 1) fetch the url // .then(function (response) { // 2) filter on 200 OK // if (response.status === 200 || response.status === 0) { // return Promise.resolve(response.blob()); // } else { // return Promise.reject(new Error(response.statusText)); // } // }) // .then(data => zip.loadAsync(data)) // 3) chain with the zip promise // .then(function (zip) { // return zip.file("Hello.txt").async("string"); // 4) chain with the text content // }) // .then(function success(text) { // console.log(text); // }, function error(e) { // console.error(e); // }); zip.file("text/file.txt", "content"); zip.forEach(function (relativePath, file) { console.log(`path: ${relativePath}, file: ${file.name}`) }); zip.generateAsync({ type: "blob" }).then(function (content) { document.body.appendChild(document.createElement("a")); document.querySelector("a").href = URL.createObjectURL(content); document.querySelector("a").download = "test.zip"; document.querySelector("a").click(); }); </script> </body> </html>
到此這篇關(guān)于詳解如何使用JSZip實(shí)現(xiàn)在瀏覽器中操作文件與文件夾的文章就介紹到這了,更多相關(guān)JSZip操作文件與文件夾內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
Bootstrap分頁(yè)插件之Bootstrap Paginator實(shí)例詳解
Bootstrap Paginator是一款基于Bootstrap的js分頁(yè)插件,功能很豐富,個(gè)人覺(jué)得這款插件已經(jīng)無(wú)可挑剔了,感興趣的朋友跟著腳本之家小編一起學(xué)習(xí)吧2016-10-10JavaScript獲取一個(gè)范圍內(nèi)日期的方法
這篇文章主要介紹了JavaScript獲取一個(gè)范圍內(nèi)日期的方法,涉及javascript操作日期的相關(guān)技巧,需要的朋友可以參考下2015-04-04Javascript:為input設(shè)置readOnly屬性(示例講解)
本篇文章主要是對(duì)Javascript中為input設(shè)置readOnly屬性的示例代碼進(jìn)行了介紹。需要的朋友可以過(guò)來(lái)參考下,希望對(duì)大家有所幫助2013-12-12