Downloading a File over HTTP

Sometimes you want to download a file that's available by HTTP, but that filename isn't part of the URL. Instead, it's put in the metadata (SourceForge does this with tracker attachments). Here's how to download the file with the right name:

package require Tcl 8.5
package require http 2

proc filegrab url {
    set token [http::geturl $url -validate 1]
    upvar #0 $token head
    set cd [dict get $head(meta) Content-Disposition]
    if {![regexp {^attachment; filename=([^ /]+)} $cd -> filename]} {
	http::cleanup $token
	return -code error "no file available"
    http::cleanup $token
    set f [open $filename {WRONLY CREAT EXCL}]
    set token [http::geturl $url -channel $f]
    http::cleanup $token
    close $f