詳解如何使用JSZip實現(xiàn)在瀏覽器中操作文件與文件夾
1. 引言
瀏覽器中如何創(chuàng)建文件夾、寫入文件呢?
答曰:可以借助JSZip這個庫來實現(xiàn)在瀏覽器內(nèi)存中創(chuàng)建文件與文件夾,最后只需下載這個.zip文件,就是最終得結果
類似的使用場景如下:
- 在線下載很多圖片,希望這些圖片能分類保存到各個文件夾并最終下載成一個zip文件
- 在線下載很多文檔,希望這些文檔能分類保存到各個文件夾并最終下載成一個zip文件
本質(zhì)上都是希望瀏覽器能創(chuàng)建文件夾和創(chuàng)建文件,最終保存成一個文件來提供下載
JSZip的GitHub站點:Stuk/jszip: Create, read and edit .zip files with Javascript (github.com)
一個可用的中文站點:JSZip參考手冊 (asprain.cn)
下面主要記錄一下基礎使用,詳細的API請參考上述文檔
2. 使用
2.1 安裝
使用NPM:
npm install jszip
使用在線CDN:
<script src="https://cdn.bootcdn.net/ajax/libs/jszip/3.10.1/jszip.js"></script>
為了可以代碼可以快速復現(xiàn),筆者這里使用CDN的方式引入
2.2 創(chuàng)建zip實例
一個JSZip實例是讀寫.zip文件的基礎
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
});
})因為Hello.txt是個文本文件,可以直接使用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文件
寫入文件與數(shù)據(jù)
zip.file("file.txt", "content");
new Promise((resolve, reject) => {
resolve(zip.file("file.txt").async("string"))
}).then(data => {
console.log(data); // 輸出:content
})寫入指定文件夾下的指定文件
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
});最后的目錄結構可以參考下圖
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>到此這篇關于詳解如何使用JSZip實現(xiàn)在瀏覽器中操作文件與文件夾的文章就介紹到這了,更多相關JSZip操作文件與文件夾內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
Bootstrap分頁插件之Bootstrap Paginator實例詳解
Bootstrap Paginator是一款基于Bootstrap的js分頁插件,功能很豐富,個人覺得這款插件已經(jīng)無可挑剔了,感興趣的朋友跟著腳本之家小編一起學習吧2016-10-10
Javascript:為input設置readOnly屬性(示例講解)
本篇文章主要是對Javascript中為input設置readOnly屬性的示例代碼進行了介紹。需要的朋友可以過來參考下,希望對大家有所幫助2013-12-12

