欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

詳解如何使用JSZip實(shí)現(xiàn)在瀏覽器中操作文件與文件夾

 更新時(shí)間:2024年04月19日 08:20:52   作者:當(dāng)時(shí)明月在曾照彩云歸  
這篇文章主要介紹了如何使用JSZip實(shí)現(xiàn)在瀏覽器中操作文件與文件夾,文中的示例代碼講解詳細(xì),具有一定的借鑒價(jià)值,有需要的小伙伴可以參考一下

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)文章

  • 微信小程序代碼上傳、審核發(fā)布小程序

    微信小程序代碼上傳、審核發(fā)布小程序

    這篇文章主要為大家詳細(xì)介紹了微信小程序代碼上傳、審核發(fā)布小程序,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下
    2019-05-05
  • Bootstrap分頁(yè)插件之Bootstrap Paginator實(shí)例詳解

    Bootstrap分頁(yè)插件之Bootstrap Paginator實(shí)例詳解

    Bootstrap Paginator是一款基于Bootstrap的js分頁(yè)插件,功能很豐富,個(gè)人覺(jué)得這款插件已經(jīng)無(wú)可挑剔了,感興趣的朋友跟著腳本之家小編一起學(xué)習(xí)吧
    2016-10-10
  • 微信小程序中的behaviors

    微信小程序中的behaviors

    behaviors是用于組件間代碼共享的特性, 類(lèi)似一些編程語(yǔ)言中的'mixin'或者'traits',這篇文章主要介紹了微信小程序中的behaviors,需要的朋友可以參考下
    2024-08-08
  • JavaScript獲取一個(gè)范圍內(nèi)日期的方法

    JavaScript獲取一個(gè)范圍內(nèi)日期的方法

    這篇文章主要介紹了JavaScript獲取一個(gè)范圍內(nèi)日期的方法,涉及javascript操作日期的相關(guān)技巧,需要的朋友可以參考下
    2015-04-04
  • 單擊某一段文字改寫(xiě)文本顏色

    單擊某一段文字改寫(xiě)文本顏色

    單擊某一段文字,改文字變?yōu)榧t色,再次單擊之后,文字又變回黑色,示例如下,需要的朋友可以參考下
    2014-06-06
  • 用JS剩余字?jǐn)?shù)計(jì)算的代碼

    用JS剩余字?jǐn)?shù)計(jì)算的代碼

    函數(shù)中首先給maxChars變量指定了值(輸入?yún)^(qū)內(nèi)最多可用的字符數(shù),注意,該變量是個(gè)可用于計(jì)算的數(shù)值)
    2008-07-07
  • 深入理解jQuery()方法的構(gòu)建原理

    深入理解jQuery()方法的構(gòu)建原理

    對(duì)于JQuery,想必大家都很熟悉。目前,很多web項(xiàng)目,在實(shí)施的過(guò)程中,考慮到各瀏覽器原生JS API的兼容性,大都會(huì)選用JQuery或類(lèi)似于JQuery這樣的框架來(lái)進(jìn)行網(wǎng)頁(yè)效果開(kāi)發(fā)。這篇文章將給大家深入介紹jQuery()方法的構(gòu)建原理,有需要的朋友們可以參考借鑒。
    2016-12-12
  • 微信小程序?qū)崿F(xiàn)下拉菜單切換效果

    微信小程序?qū)崿F(xiàn)下拉菜單切換效果

    這篇文章主要為大家詳細(xì)介紹了微信小程序?qū)崿F(xiàn)下拉菜單切換效果,篩選條件功能,文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下
    2018-11-11
  • Javascript:為input設(shè)置readOnly屬性(示例講解)

    Javascript:為input設(shè)置readOnly屬性(示例講解)

    本篇文章主要是對(duì)Javascript中為input設(shè)置readOnly屬性的示例代碼進(jìn)行了介紹。需要的朋友可以過(guò)來(lái)參考下,希望對(duì)大家有所幫助
    2013-12-12
  • 使javascript也能包含文件

    使javascript也能包含文件

    使javascript也能包含文件...
    2006-10-10

最新評(píng)論