Hi Monks!
When I am using "Location:" to redirect the page to its original state and to prevent re-sending the upload again.
I am losing the value stored in the session, I need this value to display to the user the name of the file just uploaded.
I cant understand why this happens? Why isn't the value in the session available once the Location gets called? Any suggestion why or a better why to do this?
Here is a code prototype that shows what I am trying to do:
#!/usr/bin/perl
use strict;
use warnings;
use CGI;
use HTML::Template;
use Time::Piece;
use CGI::Session;
use Data::Dumper;
my $date_ntime = localtime->strftime('%Y%m%d%H%M%S');
my $cgi = CGI->new();
# Create new session
my $session = new CGI::Session("driver:File", undef, {Directory => 'se
+sh'}) or die CGI::Session->errstr;;
my $tmpl = HTML::Template->new(filename => 'templates/mini.tmpl', die_
+on_bad_params => 0, associate => $session);
my $got_file_name = $cgi->param( 'doc_upload' ) || '';
# Store file name to use later.
$session->param("doc_uploaded", $got_file_name);
my $filename_uploaded = $session->param("doc_uploaded");
# This is the return from the redirect 'Location:'
my $conf_msg = $cgi->param( 'conf' ) || '';
process_request($got_file_name, $date_ntime) if $got_file_name ;
# To prevent re-entering data twice by refreshing page.
confirmation($conf_msg) if $conf_msg;
print $cgi->header, $tmpl->output;
exit;
sub process_request {
my ($file_name, $date_ntime ) = @_;
return unless $file_name ;
my $file_renamed .=$date_ntime.".txt";
my ($ext) = $file_name =~ /((\.[^.\s]+)+)$/;
if ($ext =~ m/\.txt|\.csv$/) {
$cgi->upload( 'doc_upload' );
my $tmp_file = $cgi->tmpFileName( $file_name );
rename( $tmp_file, $file_renamed );
chmod 0664, $file_renamed;
print 'Location: https://myserver/mini.pl?conf=1', "\r\n\r\n";
}else {
$tmpl->param(
ERROR => 1,
);
}
}
sub confirmation {
my ($message) = @_;
return unless $message;
my $text = $session->param("doc_uploaded");
#my $text = $session->param(-name=>'doc_uploaded');
$tmpl->param(
MSG_OK => 1,
#FILE_NAME => $text,
FILE_NAME => $filename_uploaded,
) if $message;
}
Here is the template file:
<!DOCTYPE html>
<html lang="en">
<head>
<title>Mini</title>
</head>
<body>
<p><b>UP-load.</b></p>
<form action="mini.pl" method="post" enctype="multipart/form-data">
<input type="file" size="40" name="doc_upload">
<input type="submit" name="doc_submit" value="Upload">
</p>
</form>
<br>
<br>
<TMPL_IF NAME="MSG_OK">
<p>Transaction was successful!</p>
<p>Filename: <TMPL_VAR NAME="FILE_NAME"></p>
</TMPL_IF>
<TMPL_IF NAME="MSG">
<p>WARNING: file <TMPL_VAR NAME="FILE_NAME"> already exists.</p>
<p>Check and try again.</p>
</TMPL_IF>
<TMPL_IF NAME="ERROR">
<p>Wrong file type.</p>
</TMPL_IF>
</body>
</html>
Thanks for looking!