...making Linux just a little more fun!

2-Cent Tips

Two-cent tip: Download whole directory as zip file

Silas S. Brown [ssb22 at cam.ac.uk]


Fri, 12 Sep 2008 15:05:13 +0100

A quick "download whole directory as zip file" CGI

If you have a large collection of files, and you put them on your webserver without any special index, then it's likely that the server will generate its own index HTML for you. This is all very well, but I recently had the tedious experience of downloading 46 separate small files from my webserver, using somebody's Windows box with Internet Explorer and a "download manager" that took me through 3 dialog boxes per click in a foreign language. Wouldn't it be nice if I could tell the web server to zip them all up and send me the zip file.

You can do this because the Unix "zip" utility (package "zip" on most distributions) is capable of writing to standard output. At a minimum, you can create a CGI script like this:

#!/bin/bash
echo Content-Type: application/zip
echo "Content-Disposition: attachment; filename=files.zip"
echo
zip -9r - *

This zips the content of the current directory, sending the result to standard output (that's what the dash - is for) and telling the Web browser that it's a zip file called files.zip.

But we can go one up on that - the following short script will list the contents of the directory, with an optional "download as zip" link that sets the filename appropriately. If you're using the small Mathopd webserver, you can edit /etc/mathopd.conf and set AutoIndexCommand to the path of this script:

export Filename="$(pwd|sed -e 's,.*/,,').zip"
if test "$QUERY_STRING" == zip; then
  echo Content-type: application/zip
  echo "Content-Disposition: attachment; filename=$Filename"
  echo
  zip -9r - *
else
  echo "Content-type: text/html; charset=utf-8"
  echo
  echo "<HTML><BODY><A HREF=\"..\">Parent directory</A> |"
  echo "<A HREF=\"./?zip\">Download $Filename</A>"
  echo "<h2>Contents of $Filename</h2><UL>"
  for N in *; do
    echo "<LI><A HREF=\"$N\">$N</A> ($(du -h "$N"|cut -f1))</LI>"
  done
  echo "</UL></BODY></HTML>"
fi

This assumes that any non-ASCII filenames will be listed in UTF-8 (otherwise change the charset).

-- 
Silas S Brown http://people.pwf.cam.ac.uk/ssb22

[ Thread continues here (21 messages/44.49kB) ]



Talkback: Discuss this article with The Answer Gang

Copyright © 2008, . Released under the Open Publication License unless otherwise noted in the body of the article. Linux Gazette is not produced, sponsored, or endorsed by its prior host, SSC, Inc.

Published in Issue 155 of Linux Gazette, October 2008

Tux