I have a zip with a bunch of folders containing one or more png-files each that I want to render to the DOM.
zip.loadAsync(file) .then(function(zip) {
zip.file('textfile.txt')
.async("string")
.then(function (content) { console.log(content); });
}, function (e) {
console.log("Error reading " + file.name + " : " + e.message); });
I can read a text file, but I'm stuck when it comes to getting the binary data from an image file.
My thought is that I should use URL.createObjectURL( blob ) to create a reference to the files and then render <img id="output" src="blob:null/341e9aeb-a794-4033-87f5-e8d075e9868a">
for each image in the zip.
How can I get the images from the zip?
Thanks!
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.
Right-click any selected JPEG image, point to "Send to" and select "Compressed (Zipped) Folder." The ZIP file is automatically created and named after the selected JPEG files. After creation, the file name is highlighted to allow easy renaming.
You can use .async("base64")
to return base64
representation of image file; prepend data:[<mediatype>][;base64],
to content
where content
is <data>
; set img
src
to data URI
string.
<script src="https://cdnjs.cloudflare.com/ajax/libs/jszip/3.1.3/jszip.min.js"></script>
<head>
<script>
window.onload = function() {
var zip = new JSZip();
function loadImage(url) {
var request = new XMLHttpRequest();
request.open("GET", url);
request.responseType = "blob";
request.onload = function() {
console.log(this.response);
var response = this.response;
var filename = "image." + response.type.split("/")[1];
zip.file(filename, response);
zip.file(filename)
.async("base64")
.then(function(content) {
console.log(content);
var img = new Image;
img.onload = function() {
document.body.appendChild(this)
}
img.src = "data:" + response.type + ";base64," + content;
},
function(e) {
console.log("Error reading "
+ file.name + " : "
+ e.message);
});
}
request.send()
}
loadImage("https://placeholdit.imgix.net/~text?txtsize=33&txt=350%C3%97150&w=350&h=150")
}
</script>
</head>
<body>
</body>
Alternatively, using .async("arraybuffer")
, Blob()
, Uint8Array()
, URL.createObjectURL()
zip.file(filename)
.async("arraybuffer")
.then(function(content) {
console.log(content);
var buffer = new Uint8Array(content);
var blob = new Blob([buffer.buffer]);
console.log(blob);
var img = new Image;
img.onload = function() {
document.body.appendChild(this)
}
img.src = URL.createObjectURL(blob);
},
function(e) {
console.log("Error reading " + file.name + " : " + e.message);
});
plnkr http://plnkr.co/edit/WURdaAqog3KTyBs4Kirj?p=preview
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With