FTP uploading a directory of files using perl

Here is a simple script to upload the files which are in a particular directory. I use something similar to automate the file uploading for my tube walking blog.

Whenever I take photos for the blog I put them into a directory with the current date as the directory name. So I have a structure like this:

c:\website\080115\
c:\website\080203\
c:\website\080205\
c:\website\080218\

I want the images in these directories to be uploaded to a new directory on the FTP server where the FTP server directory is named with the date e.g. ‘080218’.

The script is run with a command such as:

perl imageupload.pl c:\website\080218\

The script will then:

  1. Extract the date part of the directory – ‘080218’.
  2. Connect to the FTP server.
  3. Create a directory called ‘080218’ on the FTP server.
  4. Get a list of all the local files in the directory that you passed in as the argument.
  5. Upload each of these files to the FTP server.

Here’s the script. You’ll need to modify the FTP server address, username and password if you want to use it.

use File::Basename;
use Net::FTP;

my $directory = $ARGV[0];

my @parts = split(/\\/, $directory);

# get leaf directory name from whole path
my $length = $parts;
my $dateDir = $parts[$length-1];

$ftp = Net::FTP->new("ftp.yourwebsite.com", Debug => 1)
    or die "Cannot connect to hostname: $@";

$ftp->login("username", "password")
    or die "Cannot login ", $ftp->message;
	
$ftp->cwd("/website/data")
    or die "Cannot change working directory ", $ftp->message;

# create 'date named' directory on FTP server
$ftp->mkdir($dateDir);
$ftp->cwd($dateDir);

# set binary mode which is needed for image upload
$ftp->binary();

opendir(DIR, "$directory");
my @files = readdir(DIR);

foreach my $file (@files)
    {
    if (not -d $file)
        {
        # make sure the names are lower case on the server
        $file = lc($file);
        # upload the file
        $ftp->put("$directory\\$file");
        }
    }

$ftp->quit();

The script is simple, but it can easily be integrated into a more complex set of scripts to help you manage your web site.

One Comment on “FTP uploading a directory of files using perl”

  1. nice works for me thanks, is there any way though it can be modified to upload complete directorys and not just the files? example if i wantwed to upload a fiolder with several folders where would i edit the script.

    Thanks a lot in advance

    John

Leave a Reply

Your email address will not be published. Required fields are marked *

Do NOT fill this !