#!/usr/bin/perl -Tw

use CGI;
use CGI::Carp "fatalsToBrowser";

my $cgiobj = new CGI;
my $fn = $cgiobj->param('filename');		# filename
my $fh = $cgiobj->upload('filename');		# filehandle for reading
my $rInfo = $cgiobj->uploadInfo($fn);
my $byteCount = 0;

print qq~Content-Type: text/html\n\n
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN
		"http://www.w3.org/TR/html4/loose.dtd"">
<html>
	<head>
		<title>Upload Results</title>
		<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
		<style type="text/css">
			.Error, .Normal {font-size: 1.5em; font-weight: bold}
			.Error {color: #FF0000;}
		</style>
	</head>
	<body>
~;

if (!$fh || $cgiobj->cgi_error) {
	# upload error occurred
	print qq~<p class="Error">Error: Upload failed</p>~;
} else {
	$fn =~ /^.*?([^\/\\]+)$/;
	my $outname = $1;
	open OUTFILE, ">data/$outname";
	binmode OUTFILE;		# On some platforms, ensure binary file output

	while (my $bytes = read($fh, $buffer, 1024)) {
		$byteCount += $bytes;
		print OUTFILE $buffer;
	}

	close OUTFILE;

	print qq~\t\t<p class="Normal">Upload Successful.</p>\n~;
	print "\t\t<div>File size: $byteCount bytes</div>\n";
	print "\t\t<div>File type: $rInfo->{'Content-Type'}</div>\n";
}

print qq~
	</body>
</html>~;
