Wednesday, May 11, 2011

How to Add a Download Progress Bar to WWW::Mechanize in Perl

# Fetch the URL ($u) and specify a callback function to handle the content as it downloads in chunks
$m->get($u, ":content_cb" => \&callback);

# Open a new file to save the downloaded video (e.g., an FLV file). 
# If the file cannot be opened, the script will terminate (die) and print the error message ($!).
open (VID,">$i.flv") or die "$!";

# Initialize a variable to track the total number of bytes downloaded so far
$total = 0;

# Define the callback subroutine that is triggered for each chunk of data received
sub callback
{
    # Extract the arguments passed to the callback:
    # $data - the current chunk of data downloaded
    # $response - the HTTP::Response object
    # $proto - the LWP::Protocol object
    my( $data, $response, $proto ) = @_;
    
    # Write the current chunk of data to the opened file
    print VID "$data"; 
    
    # Add the length (in bytes) of the current chunk to the running total
    $total += length($data);
    
    # Retrieve the total expected size of the file from the HTTP response headers
    $size = $response->header('Content-Length');
    
    # Calculate the percentage of the file downloaded so far, round it down (floor), and print it
    print floor(($total/$size)*100), "% downloaded\n"; 
}

No comments: