Unzipit Example User File Drag and Drop

by Gregg Tavares

HTML

<p>drop a zip file here</p>
<div id="drop" style="display:none;">
  <div>drop file</div>
</div>
<div id="content"></div>

CSS

html, body { height: 100%; }
#drop {
  position: fixed;
  left: 0;
  top: 0;
  background-color: lightblue;
  width: 100%;
  height: 100%;
  pointer-events: none;
  display: flex;
  justify-content: center;
  align-items: center;
}
img, video { max-width: 200px; padding: 5px; }
pre { margin: 0 }
h2 { font-family: monospace; }

JavaScript

import {unzip, setOptions} from 'https://unpkg.com/[email protected]/dist/unzipit.module.js';

setOptions({
  workerURL: 'https://unpkg.com/[email protected]/dist/unzipit-worker.module.js',
  numWorkers: 2,
});

const contentElem = document.querySelector('#content');

const dropElem = document.querySelector('#drop');
document.body.addEventListener('dragenter', function() {
  dropElem.style.display = '';
});
document.body.addEventListener('dragexit', function() {
  dropElem.style.display = 'none';
});
document.body.addEventListener('dragover', function(ev) {
	ev.preventDefault();
}, {passive: false});

document.body.addEventListener('drop', function(ev) {
  ev.preventDefault();
  dropElem.style.display = 'none';

  if (ev.dataTransfer.items) {
    // Use DataTransferItemList interface to access the file(s)
    [...ev.dataTransfer.items].forEach((item, i) => {
      // If dropped items aren't files, reject them
      if (item.kind === "file") {
        const file = item.getAsFile();
        unzipFile(file);
      }
    });
  } else {
    // Use DataTransfer interface to access the file(s)
    [...ev.dataTransfer.files].forEach((file, i) => {
        unzipFile(file);
    });
  }
}, { passive: false });


async function unzipFile(file) {
	const {entries} = await unzip(file);
  
  contentElem.innerHTML = '';

  for (const [name, entry] of Object.entries(entries)) {
    const h2 = document.createElement('h2');
    h2.textContent = name;
    contentElem.appendChild(h2);
    
    if (entry.isDirectory) {
    	log('directory entry');
    } else if (looksLikeImage(name)) {
    	const blob = await entry.blob();
      const img = new Image();
      img.src = URL.createObjectURL(blob);
      contentElem.appendChild(img);
    } else if (looksLikeVideo(name)) {
    	const blob = await entry.blob();
      const video = document.createElement('video');
      video.src = URL.createObjectURL(blob);
      contentElem.appendChild(video);
    } else if (looksLikeAudio(name)) {
    	const blob...