vivapl has asked for the wisdom of the Perl Monks concerning the following question:

In need of wisdom

Could someone please give me an example on how to download binary files(gzipped)?

Currently by clicking on a button on my webpage, I'm getting back a file of size 0. However when I intercept the content and save it into my temp dir, it's good. I'm just about clueless at this moment.

Here is my code:(I call &dl_user($somefile))

sub read_binary { local($fname) = @_; open(FILE, "<$fname") || return ''; while(<FILE>){ $spcontent .= $_; } close(FILE); $spcontent; } sub dl_user { ($loc)=@_; $filename = $loc; $filename =~ s/.+\/([^\/]+)$/$1/; $filename =~ s/.+\\([^\\]+)$/$1/; print "Content-Type: application/x-binary\n"; print"Content-Disposition:attachment;filename=$filename\n\n"; &read_binary($loc); }

Thanks in advance!

Edit by tye, title, remove extra P tags

Replies are listed 'Best First'.
Re: How to offer binary files for download via CGI ?
by JamesNC (Chaplain) on Jul 22, 2003 at 21:51 UTC
    did you try binmode?
    sub read_binary { local($fname) = @_; open(FILE, "<$fname") || return ''; binmode FILE; while(<FILE>){ $spcontent .= $_; } close(FILE); $spcontent; }

    JamesNC
Re: How to offer binary files for download via CGI ?
by sgifford (Prior) on Jul 22, 2003 at 21:48 UTC

    The sample code you've posted doesn't do anything with the file's contents; it just reads them, puts them in a variable, then returns it as the result of dl_user. Perhaps it's printed elsewhere, but if not that's part of your problem.

    The usual content type for arbitrary binary data is application/octet-stream, although I don't think that's part of your current problem.

    It can also be awkward to read binary files with the diamond operator <FILE>, since line breaks don't occur in any particular place. It's usually best to use read, but again I don't think this is causing the problem you're seeing.

      <> Do the Right Thing with bin slurps -- although read is better. octet-stream seems to have some issues with random browsers showing the file instead of saving. I will have to go back and look what type i used after doing a ton of tests with many browsers -- I just hvae it stuck in my mind that octet-stream failed a bunch of download tests last time I did this.

      -Waswas
Re: How to offer binary files for download via CGI ?
by Zaxo (Archbishop) on Jul 22, 2003 at 20:51 UTC

    I think you should look into LWP::UserAgent. That will handle most of the details. All you need to do is tell it what you want. There is a unified interface for several protocols, including http and ftp.

    After Compline,
    Zaxo

      LWP::UserAgent is for being an http client. When was the last time a client used CGI or needed to print "Content-Type: application/x-binary\n";?

      --Bob Niederman, http://bob-n.com