Maverick
Maverick

Reputation: 587

Perl script for Downloading the file from web

I am trying to automate one of my task where i have to download a last 5 releases of some softwares let say Google talk from http://www.filehippo.com/download_google_talk/.

I have never done such type of programming i mean, to interact with Web through perl .I have just read and came to know that through CGI module we can implement this thing so i tried with this module.

If some body can give me better advice then please you are welcome :)

My code :

#!/usr/bin/perl 

use strict;
use warnings;
use CGI; 
use CGI::Carp qw/fatalsToBrowser/;

my $path_to_files =   'http://www.filehippo.com/download_google_talk/download/298ba15362f425c3ac48ffbda96a6156';

my $q = CGI->new;

my $file = $q->param('file') or error('Error: No file selected.');
print "$file\n";

if ($file =~ /^(\w+[\w.-]+\.\w+)$/) {
   $file = $1;
}
else {
   error('Error: Unexpected characters in filename.');
}   

if ($file) {
  download($file) or error('Error: an unknown error has occured. Try again.');
}  

sub download 
{

open(DLFILE, '<', "$path_to_files/$file") or return(0);
print $q->header(-type            => 'application/x-download',
                 -attachment      => $file,
                  'Content-length' => -s "$path_to_files/$file",
   );
  binmode DLFILE;
   print while <DLFILE>;
   close (DLFILE);
   return(1);
}

sub error {
   print $q->header(),
         $q->start_html(-title=>'Error'),
         $q->h1($_[0]),
         $q->end_html;
   exit(0);
}

In above code i am trying to print the file name which i wan to download but it is displaying error message.I am not able to figure it out why this error "Error: No file selected." is comming.

Upvotes: 1

Views: 7333

Answers (1)

user1126070
user1126070

Reputation: 5069

Sorry, but you are in the wrong track. Your best bet is this module: http://metacpan.org/pod/WWW::Mechanize

This page contain a lot of example to start with: http://metacpan.org/pod/WWW::Mechanize::Examples

It could be more elegant but I think this code easier to understand.

use strict;
use warnings;

my $path_to_files =   'http://www.filehippo.com/download_google_talk/download/298ba15362f425c3ac48ffbda96a6156';
my $mech = WWW::Mechanize->new();
$mech->get( $path_to_files );
$mech->save_content( "download_google_talk.html" );#save the base to see how it looks  like
foreach my $link ( $mech->links() ){ #walk all links
    print "link: $link\n";
    if ($link =~ m!what_you_want!i){ #if it match
        my $fname = $link;
        $fname =~ s!\A.*/!! if $link =~ m!/!;
        $fname .= ".zip"; #add extension
        print "Download $link to $fname\n";
        $mech->get($link,":content_file" => "$fname" );#download the file and stoore it in a fname.     
    }
}

Upvotes: 2

Related Questions