画像をダウンロードするCGI

友達に聞いたりしながら、苦労した。

#!/usr/bin/perl -w

use CGI::Carp qw(fatalsToBrowser);
use CGI;
use File::MMagic;

&main;

sub main {
    my $file = "test.gif";
    my $type = File::MMagic->new->checktype_filename($file);

    my $cgi = CGI->new;
    print $cgi->header(
      -type => $type,
      -attachment => $file
    );

    open(File,$file) or die "Can't open file";
    binmode(File);
    binmode(STDOUT);
    while(<File>) {print;}
    close(File);
}

1;

バイナリをダウンロードさせるには、binmodeってのは理解できてたんだけど、そのあとの while でprintする部分で意外とつまった。


メモメモ・・。