Search code examples
windows-8local-storagewinjsjszip

How can I save a zip file to local storage in a win8 app using JSZip?


I'm able to create the JSZip object in my code, but I'm having trouble saving that to local storage in my windows 8 app. The examples I'm able to find set the browser's location.href to trigger a download, which isn't really an option for me.

I've included my code below. The zip file I end up with is invalid and can't be opened. Any help would be appreciated.

For reference: JSZip

        function _zipTest() {
        var dbFile = null;
        var zipData = null;
        Windows.Storage.StorageFile.getFileFromPathAsync(config.db.path)
            .then(function (file) {
                dbFile = file;
                return Windows.Storage.FileIO.readBufferAsync(file);
            })
            .then(function (buffer) {
                //Read the database file into a byte array and create a new zip file
                zipData = new Uint8Array(buffer.length);
                var dataReader = Windows.Storage.Streams.DataReader.fromBuffer(buffer);
                dataReader.readBytes(zipData);
                dataReader.close();

                var localFolder = Windows.Storage.ApplicationData.current.localFolder;
                return localFolder.createFileAsync(dbFile.displayName.concat('.zip'), Windows.Storage.CreationCollisionOption.replaceExisting)
            })
            .then(function (file) {
                //Write the zip data to the new zip file
                var zip = new JSZip();
                zip.file(dbFile.displayName, zipData);
                var content = zip.generate();

                return Windows.Storage.FileIO.writeTextAsync(file, content);
            });
    }

Solution

  • you can do something on these lines. This code seem to generate valid .zip file in the temp folder.

        var zip = new JSZip();
        var storage = Windows.Storage;
        storage.StorageFile.getFileFromApplicationUriAsync(new Windows.Foundation.Uri('ms-appx:///images/logo.png')).then(function ongetfile(file)
        {
            var blob = MSApp.createFileFromStorageFile(file);
            var url = URL.createObjectURL(blob, { oneTimeOnly: true });
            return WinJS.xhr({ url: url, responseType: 'arraybuffer' });
        }).then(function onreadbuffer(req)
        {
            var b = req.response;
            zip.file('logo.png', b);
            return storage.ApplicationData.current.temporaryFolder.createFileAsync('a.zip', storage.CreationCollisionOption.replaceExisting);
        }).then(function onnewfile(out)
        {
            var content = zip.generate({ type: 'uint8array' });
            return storage.FileIO.writeBytesAsync(out, content);
        }).then(null, function onerror(error)
        {
            // TODO: error handling
        });