Last active
November 15, 2018 23:53
-
-
Save MartinN3/fd51afcca55f34bf3fcdf4ef5516754c to your computer and use it in GitHub Desktop.
JSzip test
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Run in console on loremflicker.com | |
class ScriptLoader { | |
constructor(scriptUrl) { | |
this.script = document.createElement('script'); | |
this.script.src = scriptUrl; | |
// this.head = document.querySelector('head'); | |
this.firstScriptTag = document.getElementsByTagName('script')[0]; | |
} | |
load() { | |
return new Promise((resolve, reject) => { | |
this.script.async = true; | |
this.script.onload = () => resolve(); | |
this.script.onerror = () => reject(); | |
// this.head.appendChild(this.script); | |
this.firstScriptTag.parentNode.insertBefore(this.script, this.firstScriptTag); | |
}); | |
} | |
} | |
new ScriptLoader("https://cdnjs.cloudflare.com/ajax/libs/jszip-utils/0.0.2/jszip-utils.min.js").load().then(() => { | |
new ScriptLoader("https://cdnjs.cloudflare.com/ajax/libs/jszip/3.1.5/jszip.min.js").load().then(() => { | |
new ScriptLoader("https://cdnjs.cloudflare.com/ajax/libs/FileSaver.js/1.3.8/FileSaver.min.js").load().then(() => { | |
let zip = new JSZip(); | |
zip.file("Hello.txt", "Hello World\n"); | |
var img = zip.folder("images"); | |
img.file('test.jpg', urlToPromise('https://loremflickr.com/g/320/240/paris'), {base64: true}); | |
zip.generateAsync({type:"blob"}) | |
.then(function(content) { | |
// see FileSaver.js | |
saveAs(content, "example.zip"); | |
}); | |
}) | |
.catch((e) => { | |
console.log(e); | |
}) | |
}) | |
}) | |
function urlToPromise(url) { | |
return new Promise((resolve, reject) => { | |
JSZipUtils.getBinaryContent(url, function (err, data) { | |
if(err) { | |
reject(err); | |
} else { | |
resolve(data); | |
} | |
}); | |
}); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment