Manage uploads with perl

From ProVide DocWiki
Jump to: navigation, search

Example 1

For this example we shall make the server lookup data online based on uploaded files.

The script we will be using for this example is the following:

use LWP::Simple;
use File::Basename;

$ENV{'CYGWIN'} = "winsymlinks:nativestrict";

$source = "/cygdrive/e/Uploads/";
$target = "/cygdrive/e/Filtered/";

%codes = (
	1 => "Filetype 1",
	2 => "Filetype 2",
	3 => "Filetype 3"
);

($command, $file) = @ARGV;

if (defined $file) {
	$file =~ tr/"//d;
	($filename, $path, $suffix) = fileparse($file, qr/\.[^.]*/);
	if ($path eq "./" && index($filename, ':\\') != -1) {
		$file =~ s/\\/\//g;
		$file =~ s/(.+?):\//\/cygdrive\/$1\//ig;
		($filename, $path, $suffix) = fileparse($file, qr/\.[^.]*/);
		if (lc $path eq lc $source) {
			processFile($source.$filename.$suffix);
		}
	}
} else {
	@files = <"$source*">;
	foreach $file (@files) {
		processFile($file);
	}
}

sub processFile {
	my ($file) = @_;
	($filename, $path, $suffix) = fileparse($file, qr/\.[^.]*/);
	if ($filename =~ m/(.*?)_(.*)/) {
		$id = $1;
		$code = $2;
		
		$html = get("http://www.database.com/search?id=$id");
		if ($html =~ m/<li>Category: (.*?)<\/li>/s) {
			$category = trim($1);
		}
		[...]
		
		$code = $codes{$code};
		
		if ($command eq "create") {
			mkdir "$target/$category";
			symlink($file, "$target/$category/$code$suffix");
		} elsif ($command eq "remove") {
			unlink("$target/$category/$code$suffix");
			rmdir "$target/$category";
		}
	}
};


1. The first step once we've done the script is to save it down to a '.pl' file (name it something like OnUploadEndScript to easily keep track of it) and save it in a script folder.

2. To make this script trigger after a file has been uploaded to the server we first need to go on the admin interface for our ProVide server and find "Events and Messages" under the first tab.

3. In the "Events and Messages" window we click on the drop-down menu and select "OnUploadEnd". Everything in the message field will either be written to the server logg or we can execute scripts and even send arguments with it.

The text we will write in the message area of the "Events and Messages" window is the following:

%EXECUTE("c:\cygwin64\bin\perl.exe" "c:\scripts\OnUploadEndScript.pl" create "%LOCAL_FILENAME%")%


This will make the script that we just created execute after a file is done uploading, it will also provide the "%LOCAL_FILENAME%" which is the full path to the file that was used in the upload.