user2388062
user2388062

Reputation: 1

Perl download from url to local drive

I want to offer my visitors a file for download to their local machine (e.g. the Download directory in case of Windows7). The code below works perfectly well, but only if the file is located on the same machine as the script:

#!/usr/bin/perl

my $path = "samples/10000.mp3"; ##PATH_TO_FILE
my $file = "10000.mp3";

print "Content-Type:application/octet-stream; name=\"$file\"\r\n";
print "Content-Disposition: attachment; filename=\"$file\"\r\n\n";

open( FILE, $path );

while(read(FILE, $buffer, 100) ){
print("$buffer");
}

The problem is that the file in question is located on another machine, so I have to get the url for download. I thought the coding below would do the trick, but no matter what I try, I end up with a downloaded file of 0 bytes. Can someone please tell me what I am doing wrong?

#!/usr/bin/perl

use LWP::Simple;
my $url = 'http://<sampleurl>.com';
my $file = '10000.mp3';

my $path = get($url);

print "Content-Type:application/octet-stream; name=\"$file\"\r\n";
print "Content-Disposition: attachment; filename=\"$file\"\r\n\n";

open my $fh, '+>', $path;
while(read($fh, $buffer, 100) ){
print("$buffer");
}

Upvotes: 0

Views: 2010

Answers (1)

Greg Bacon
Greg Bacon

Reputation: 139681

The get method in LWP::Simple returns the content, not the path to a file containing the content.

Once you have the content bits, write them to the standard output along with the header. Change your second program to

#! /usr/bin/perl

use LWP::Simple;

my $url = 'http://<sampleurl>.com';
my $file = '10000.mp3';

my $bits = get($url);
die "$0: get $url failed" unless defined $bits;

binmode STDOUT or die "$0: binmode: $!";

print qq[Content-Type:application/octet-stream; name="$file"\r\n],
      qq[Content-Disposition: attachment; filename="$file"\r\n],
      qq[\r\n],
      $bits;

Upvotes: 2

Related Questions