↓ Skip to main content
  1. Posts/

Open zip files in Windows 8 Modern UI ( Metro )

·
Rubén Infante Docio
Author
Rubén Infante Docio
Software engineer

Today we are going to see how to open a javascript file, using a filepicker, in javascript applications for Windows 8, and process the files individually one by one.

Steps
#

  1. First we download the zip.js library from here these are the files we are interested in.

    js zip files
    inflate.js(compress), deflate.js (unzip)

  2. // Creamos el objeto picker, con las opciones deseadas
        var openPicker = new Windows.Storage.Pickers.FileOpenPicker();
        openPicker.viewMode = Windows.Storage.Pickers.PickerViewMode.list;
        openPicker.suggestedStartLocation = Windows.Storage.Pickers.PickerLocationId.documentsLibrary;
        //Establecemos los formatos que queremos capturar
        openPicker.fileTypeFilter.replaceAll([".zip", ".ZIP"]);
    
        // pickSingleFilesAsync si solo queremos uno
        openPicker.pickMultipleFilesAsync().then(function (file) {
            if(file.size >0){
                for (var i = 0; i < file.size; i++) {
                    //imaginemos que contiene ficheros de texto
                    file[i].openReadAsync().then(function (stream) {
                        if (myFile) {
                            //Creamos un blob del archivo zip
                            var blob = MSApp.createBlobFromRandomAccessStream(myFile.contentType, stream);
    
                            //Para blob
                            zip.createReader(new zip.BlobReader(blob), function (reader) {
                                // Obtenemos los ficheros
                                reader.getEntries(function (entries) {
                                    //Accedemos a cada fichero
                                    entries.forEach(function (item) {
                                        item.getData(new zip.TextWriter(), function (data) {
                                            //"data" contiene el texto del fichero
                                        });
    
                                    });
    
                                });
    
                            }, function (error) {
                                // Error callback
                            });
    
                        }
                    });
    
                }
            } else {
                //Se ha presionado cancelar
            }
        });
  3. As we can see, in this simple way, we will be able to open zip files with zip.js and winJS.

Notes
#

This is applicable to text files (inside the zip), with UTF-8 encoding, soon we will see how to work with other encodings such as ISO 5598-1, ISO 5598-15 etc.

Wise note:
#

Substituting

 zip.createReader(new zip.BlobReader(blob), function (reader) {

by

zip.createReader(new zip.HttpRangeReader(url), function (reader) {

We will be able to access files hosted on a website.

Related