Form content enctype

On my previous post, Tricky way to instantiate a class in Perl I shared how to instantiate a class in a tricky way. On that post, while I did the instantiation of my CGI class it was supposed that the Form was posted with its default content enctype – ‘application/x-www-form-urlencoded’.

More details about Form content enctype:

http://www.w3.org/TR/html4/interact/forms.html

enctype = content-type [CI]This attribute specifies the content type used to submit the form to the server (when the value of method is “post”). The default value for this attribute is “application/x-www-form-urlencoded”. The value”multipart/form-data” should be used in combination with the INPUT element, type=”file”.

 By default, Form is posted with application/x-www-form-urlencoded type and its content will be as below,

Content-Type: application/x-www-form-urlencoded

userid=user2&dbid=db1&Submit=submit

# Here it is easily to strip its key/value

 However for type multipart/form-data, its content will be,

Content-Type: multipart/form-data; boundary=—————————11619042012130902275583102315 —————————–11619042012130902275583102315 Content-Disposition: form-data; name=”dbsid” fx2 —————————–11619042012130902275583102315 Content-Disposition: form-data; name=”appsschema” APPSSHEMA —————————–11619042012130902275583102315 Content-Disposition: form-data; name=”appspass” APPSPASSWORD —————————–11619042012130902275583102315 Content-Disposition: form-data; name=”systemschema” SYSTEMSCHEMA —————————–11619042012130902275583102315 Content-Disposition: form-data; name=”systempass” MANAGER —————————–11619042012130902275583102315 Content-Disposition: form-data; name=”Submit” Submit—————————–11619042012130902275583102315–

# It is a bit difficult to strip key/value from it. To support that I added a method parseContent() to retrieve the key/value pairs in the same format as ‘application/x-www-form-urlencoded’ – key=value&key1=value1&key2=value2

# check whether form type is “multipart/form-data”

# if yes, it will retrieve it in format of ‘key=value&key1=value1’.

sub parseContent{
my $paramstr = shift;
my $pos = index($paramstr, "name=");
my $replaced = substr($paramstr, 0, $pos);
my @array = split(/$replaced/, $paramstr);
my $s = "";
my $count = 0;
my $sclr = scalar(@array) - 1;
foreach my $line (@array){
if(($count > 0) and ($count < $sclr)){
$line =~ s/name=//;
$line =~ s/\s+/=/;
$line =~ s/^\s*|\s*$//g;
chomp($line);
$s .= $line . "\&";
}
$count++;
}
$s = substr($s,0,length($s)-1);
return $s;
}

sub getParams{
my $s = shift;
#$s = "hahaid=haha1&abcid=abc2&Submit=submit";
chomp($s);
if ($s =~ m/form-data/){
$s = parseContent($s);
}
my %params = {};
my @pairs = split(/\&/,$s);
foreach (@pairs){
my ($key, $value) = split(/=/,$_);
$params{$key} = $value;
}
return %params;
}