- Saved searches
- Use saved searches to filter your results more quickly
- gildas-lormeau/zip.js
- Name already in use
- Sign In Required
- Launching GitHub Desktop
- Launching GitHub Desktop
- Launching Xcode
- Launching Visual Studio Code
- Latest commit
- Git stats
- Files
- README.md
- JSZip
- Example
- Installation
- Support
- Getting help
- How to use JSZip
- Getting the object
- In a browser
- In nodejs
- Basic manipulations
- Generate a zip file
- Read a zip file
- JSZip Создаем .zip файлы
- Поддерживаемые Браузеры
- Документация
Saved searches
Use saved searches to filter your results more quickly
You signed in with another tab or window. Reload to refresh your session. You signed out in another tab or window. Reload to refresh your session. You switched accounts on another tab or window. Reload to refresh your session.
JavaScript library to zip and unzip files supporting multi-core compression, compression streams, zip64, split files and encryption.
gildas-lormeau/zip.js
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Name already in use
A tag already exists with the provided branch name. Many Git commands accept both tag and branch names, so creating this branch may cause unexpected behavior. Are you sure you want to create this branch?
Sign In Required
Please sign in to use Codespaces.
Launching GitHub Desktop
If nothing happens, download GitHub Desktop and try again.
Launching GitHub Desktop
If nothing happens, download GitHub Desktop and try again.
Launching Xcode
If nothing happens, download Xcode and try again.
Launching Visual Studio Code
Your codespace will open once ready.
There was a problem preparing your codespace, please try again.
Latest commit
Git stats
Files
Failed to load latest commit information.
README.md
zip.js is a JavaScript open-source library (BSD-3-Clause license) for compressing and decompressing zip files. It has been designed to handle large amounts of data. It supports notably multi-core compression, native compression with compression streams, files larger than 4GB with Zip64, split zip files and data encryption.
import BlobReader, BlobWriter, TextReader, TextWriter, ZipReader, ZipWriter, > from "https://deno.land/x/zipjs/index.js"; // ---- // Write the zip file // ---- // Creates a BlobWriter object where the zip content will be written. const zipFileWriter = new BlobWriter(); // Creates a TextReader object storing the text of the entry to add in the zip // (i.e. "Hello world!"). const helloWorldReader = new TextReader("Hello world!"); // Creates a ZipWriter object writing data via `zipFileWriter`, adds the entry // "hello.txt" containing the text "Hello world!" via `helloWorldReader`, and // closes the writer. const zipWriter = new ZipWriter(zipFileWriter); await zipWriter.add("hello.txt", helloWorldReader); await zipWriter.close(); // Retrieves the Blob object containing the zip content into `zipFileBlob`. It // is also returned by zipWriter.close() for more convenience. const zipFileBlob = await zipFileWriter.getData(); // ---- // Read the zip file // ---- // Creates a BlobReader object used to read `zipFileBlob`. const zipFileReader = new BlobReader(zipFileBlob); // Creates a TextWriter object where the content of the first entry in the zip // will be written. const helloWorldWriter = new TextWriter(); // Creates a ZipReader object reading the zip content via `zipFileReader`, // retrieves metadata (name, dates, etc.) of the first entry, retrieves its // content via `helloWorldWriter`, and closes the reader. const zipReader = new ZipReader(zipFileReader); const firstEntry = (await zipReader.getEntries()).shift(); const helloWorldText = await firstEntry.getData(helloWorldWriter); await zipReader.close(); // Displays "Hello world!". console.log(helloWorldText);
import BlobReader, ZipReader, ZipWriter, > from "https://deno.land/x/zipjs/index.js"; // ---- // Write the zip file // ---- // Creates a TransformStream object, the zip content will be written in the // `writable` property. const zipFileStream = new TransformStream(); // Creates a Promise object resolved to the zip content returned as a Blob // object retrieved from `zipFileStream.readable`. const zipFileBlobPromise = new Response(zipFileStream.readable).blob(); // Creates a ReadableStream object storing the text of the entry to add in the // zip (i.e. "Hello world!"). const helloWorldReadable = new Blob(["Hello world!"]).stream(); // Creates a ZipWriter object writing data into `zipFileStream.writable`, adds // the entry "hello.txt" containing the text "Hello world!" retrieved from // `helloWorldReadable`, and closes the writer. const zipWriter = new ZipWriter(zipFileStream.writable); await zipWriter.add("hello.txt", helloWorldReadable); await zipWriter.close(); // Retrieves the Blob object containing the zip content into `zipFileBlob`. const zipFileBlob = await zipFileBlobPromise; // ---- // Read the zip file // ---- // Creates a BlobReader object used to read `zipFileBlob`. const zipFileReader = new BlobReader(zipFileBlob); // Creates a TransformStream object, the content of the first entry in the zip // will be written in the `writable` property. const helloWorldStream = new TransformStream(); // Creates a Promise object resolved to the content of the first entry returned // as text from `helloWorldStream.readable`. const helloWorldTextPromise = new Response(helloWorldStream.readable).text(); // Creates a ZipReader object reading the zip content via `zipFileReader`, // retrieves metadata (name, dates, etc.) of the first entry, retrieves its // content into `helloWorldStream.writable`, and closes the reader. const zipReader = new ZipReader(zipFileReader); const firstEntry = (await zipReader.getEntries()).shift(); await firstEntry.getData(helloWorldStream.writable); await zipReader.close(); // Displays "Hello world!". const helloWorldText = await helloWorldTextPromise; console.log(helloWorldText);
Adding concurrently multiple entries in a zip file
import BlobWriter, HttpReader, TextReader, ZipWriter, > from "https://unpkg.com/@zip.js/zip.js/index.js"; const README_URL = "https://unpkg.com/@zip.js/zip.js/README.md"; getZipFileBlob() .then(downloadFile); async function getZipFileBlob() const zipWriter = new ZipWriter(new BlobWriter("application/zip")); await Promise.all([ zipWriter.add("hello.txt", new TextReader("Hello world!")), zipWriter.add("README.md", new HttpReader(README_URL)), ]); return zipWriter.close(); > function downloadFile(blob) document.body.appendChild(Object.assign(document.createElement("a"), download: "hello.zip", href: URL.createObjectURL(blob), textContent: "Download zip file", >)); >
JSZip
JSZip is a javascript library for creating, reading and editing .zip files, with a lovely and simple API.
Current version : v3.10.1
License : JSZip is dual-licensed. You may use it under the MIT license or the GPLv3 license. See LICENSE.markdown.
Example
Installation
With npm : npm install jszip
With bower : bower install Stuk/jszip
With component : component install Stuk/jszip
Manually : download JSZip and include the file dist/jszip.js or dist/jszip.min.js
Installed ? Great ! You can now check our guides and examples !
Support
Opera | Firefox | Safari | Chrome | Internet Explorer | Node.js |
---|---|---|---|---|---|
Yes | Yes | Yes | Yes | Yes | Yes |
Tested with the latest version | Tested with 3.0 / 3.6 / latest version | Tested with the latest version | Tested with the latest version | Tested with IE 6 / 7 / 8 / 9 / 10 | Tested with node.js 0.10 / latest version |
Getting help
Having trouble ? We’d like to help !
- Try the FAQ, it has answers to common questions.
- If you’re looking for information about a specific method, try the documentation.
- Check the examples.
- Report bugs in our Bug tracker.
How to use JSZip
An instance of JSZip represents a set of files. You can add them, remove them, modify them. You can also import an existing zip file or generate one.
Getting the object
In a browser
For a browser, there are two interesting files : dist/jszip.js and dist/jszip.min.js (include just one).
If you use an AMD loader (RequireJS for example) JSZip will register itself : you just have to put the js file at the right place, or configure the loader (see here for RequireJS).
Without any loader, JSZip will declare in the global scope a variable named JSZip .
In nodejs
In nodejs, you can require it :
Basic manipulations
The first step is to create an instance of JSZip :
On this instance, we can add (and update) files and folders with .file(name, content) and .folder(name) . They return the current JSZip instance so you can chain the calls.
// create a file zip.file("hello.txt", "Hello[p my)6cxsw2q"); // oops, cat on keyboard. Fixing ! zip.file("hello.txt", "Hello World\n"); // create a file and a folder zip.file("nested/hello.txt", "Hello World\n"); // same as zip.folder("nested").file("hello.txt", "Hello World\n");
With .folder(name) , the returned object has a different root : if you add files on this object, you will put them in the created subfolder. This is just a view, the added files will also be in the “root” object.
var photoZip = zip.folder("photos"); // this call will create photos/README photoZip.file("README", "a folder with photos");
You can access the file content with .file(name) and its getters :
zip.file("hello.txt").async("string").then(function (data) // data is "Hello World\n" >); if (JSZip.support.uint8array) zip.file("hello.txt").async("uint8array").then(function (data) // data is Uint8Array >); >
You can also remove files or folders with .remove(name) :
zip.remove("photos/README"); zip.remove("photos"); // same as zip.remove("photos"); // by removing the folder, you also remove its content.
Generate a zip file
With .generateAsync(options) or .generateNodeStream(options) you can generate a zip file (not a real file but its representation in memory). Check this page for more information on how to write / give the file to the user.
var promise = null; if (JSZip.support.uint8array) promise = zip.generateAsync(type : "uint8array">); > else promise = zip.generateAsync(type : "string">); >
Read a zip file
With .loadAsync(data) you can load a zip file. Check this page to see how to do properly (it’s more tricky that it seems).
var new_zip = new JSZip(); // more files ! new_zip.loadAsync(content) .then(function(zip) // you now have every files contained in the loaded zip zip.file("hello.txt").async("string"); // a promise of "Hello World\n" >);
JSZip Создаем .zip файлы
Итак давайте разберем, что тут происходит.
Создается экземпляр нашего zip архива, класс JSZip,.
Далее мы можем добавлять в него любые данные, допустим Hello.txt, также можно добавить папку images.
Далее положить в нее smile.gif, все это завернуть, и отдать вам как zip фаил.
Поддерживаемые Браузеры
Opera | Firefox | Safari | Chrome |
---|---|---|---|
7.5+ Имя файла «default.zip» | 3.0+ Имя файла набор из символов алфавита с расширением «.part» | Имя файла «Unknown» ( у меня Загруженное ) без расширения | Имя файла «download.zip» |
Думаю про IE я промолчу 🙂
Документация
new JSZip([compressionMethod])
compressionMethod, строка. Метод компрессии используемый в .zip файле.
Доступные методы.
«STORE» без компрессии, по умлочанию.
«DEFLATE» стандартная zip компрессия, нужен файл jszip-deflate.js
var zip = new JSZip(); // тоже что и new JSZip("STORE"); var zip = new JSZip("DEFLATE");
add(name, data [,options])
Добавить файл в наш zip архив. Поддерживает цепочку (chaining)
Опции (options)
base64, булево. Поставьте в true если data кодирована в base64. К примеру картинка из canvas.
binary, булево. По умолчанию в true если data в base64, иначе false
date, Дата. Используйте чтобы установить дату последнего изменения файла. Иначе будет использовано текущее время.
zip.add("Hello.txt", "Hello World\n"); zip.add("smile.gif", "R0lGODdhBQAFAIACAAAAAP/eACwAAAAABQAFAAACCIwPkWerClIBADs=", ); zip.add("magic.txt", "U2VjcmV0IGNvZGU=", ); zip.add("Xmas.txt", "Ho ho ho !", ); zip.add("animals.txt", "dog,platypus\n").add("people.txt", "james,sebastian\n");
Результат: Hello.txt, smile.gif, magic.txt, Xmas.txt, animals.txt, people.txt
folder(name)
zip.folder("images"); zip.folder("css").add("style.css", "body "); // or specify an absolute path (using forward slashes) zip.add("css/font.css", "body ")
Результат: images/, css/, css/style.css, css/font.css
find(needle)
Сравнить строку или регулярное выражение со всеми именами файлов и вернуть объект с информацией по каждому совпадению.
zip.add("Readme", "Hello World!\n"); zip.add("Readme.French", "Bonjour tout le monde!\n"); zip.add("Readme.Pirate", "Ahoy m'hearty!\n"); zip.find("Readme"); // only finds "Readme" zip.find(/^Readme/); // Regular expression finds all three
remove(name)
Удалить файл или папку
zip.add(»Hello.txt», «Hello World\n»);
zip.add(«temp.txt», «nothing»).remove(«temp.txt»);
zip.add("Hello.txt", "Hello World\n"); zip.folder("css").add("style.css", "body "); zip.remove("Hello.txt").remove("css");
generate(asBytes = false)
Генерирует zip архив. По умолчанию кодированный в base64, передайте true чтобы получить ‘голую’ byte строку.
content = zip.generate(); location.href="data:application/zip;base64,"+content; content = zip.generate(true); for (var c = 0; c < content.length; c++) < console.log(content.charCodeAt(c)); // do other things >
Материал подготовлен в редакторе «Руки&Клавиатура»