Perl CGI: How to asynchronously upload multiple files

Date March 14th, 2016 Author Vitaly Agapov

If you pass by then just pass by.

Alexey Ivanov «Dormitory-on-Blood»

async

This is a quite frequently used control in the modern web UIs. The user just selects file or files as usual but then he has no need to submit the form and wait for the page to reload. The files are uploaded immediately by Ajax and the result can be seen immediately too.

jQuery makes this task trivial from the frontend point of view but the server side is not so clear. Especially if you use Perl. So I will try eliminate the lack of information with this small post.

Let’s start with the frontend anyway. We’ll assume that we have such an object in our html:

<form action="#" enctype="multipart/form-data" method="post" id="form_file_upload">
   <label for="file_upload">Load from file:</label>
   <input type="file" name="file_upload" id="file_upload" multiple>
</form>

And we also have such a JS:

$(document).ready(function(){
  $('input[type=file]').on('change', uploadFiles);
});
function uploadFiles(event) {
  files = event.target.files;
  event.stopPropagation(); // Stop stuff happening
  event.preventDefault();  // Totally stop stuff happening
  // Create a formdata object and add the files
  var data = new FormData();
  $.each(files, function(key, value) {
     data.append(key, value);
  });
  $.ajax({
     url: '/cgi-bin/upload.pl',
     type: 'POST',
     data: data,
     cache: false,
     dataType: 'json',
     processData: false,
     contentType: false,
     success: function(data, textStatus, jqXHR) {
        if(typeof data.error === 'undefined') {
            handleParsedResults(data.data);
        }
        else {
            console.log('ERRORS: ' + data.error);
        }
     },
     error: function(jqXHR, textStatus, errorThrown) {
        console.log('ERROR: ' + textStatus);
     }
  });
}

Of course this snippet is for case when backend returns some JSON. In any other case the code will we slightly different.

This was just an introduction. Let’s see what should be in upload.pl script.

#!/usr/bin/perl
use JSON;
use CGI;
my $cgi=new CGI();
print "\n";
my $fileCount = 0;
# Iterate over uploaded files
foreach my $tmpfile (keys %{$cgi->{".tmpfiles"}}) {
   # Define the original filename
   my $filename = $cgi->{".tmpfiles"}->{$tmpfile}->{'info'}->{'Content-Disposition'};
   if ( $filename =~ /filename=\"(.+?)\"/ ) {
      $filename = $1;
   } else {
      $filename = "tmpfile$fileCount";
   }
   # Define the full path to the temporary saved file
   my $cgitmpfile=$cgi->{".tmpfiles"}->{$tmpfile}->{'name'}->as_string();

   # Here we can do the magic with all the files.
   # We know the current path to TMP file ($cgitmpfile)
   # And the original name of the file ($filename)
   # So we can move it to some folder we'd like to save it in or just parse it
}
my $result;
$result{data} = "some result text";
$result{error} = $error if ( $error );
print to_json( \%result );
exit;

This is kind of skeleton for any application. I will be glad if it is useful for somebody.

Tags: ,
Category: Perl, Web-dev | 2 Comments »

Comments

2 комментариев на “Perl CGI: How to asynchronously upload multiple files”

  1. idrees

    Thanks for stopping by my page! I’m Idrees Leech.
    Even though I jokingly credit my mother for my writing talent, I know that it is a ability I have fostered from childhood. Though my aunt is a writer, I also started out young.
    I’ve always had a way with words, according to my favorite educator. I was always so excited in science when we had to do a research assignment .
    Now, I help current learners achieve the grades that have always come easily to me. It is my way of giving back to communities because I understand the troubles they must overcome to graduate.

    Idrees – Professional Writer – http://www.bestexambooks.comCorp

  2. raiden

    Good day and welcome to my blog . I’m Raiden.
    I have always dreamed of being a writer but never dreamed I’d make a career of it. In college, though, I aided a fellow student who needed help. She could not stop telling me how well I had done. Word got around and someone asked me for to help them just a week later. This time they would compensate me for my work.
    During the summer, I started doing academic writing for students at the local college. It helped me have fun that summer and even funded some of my college tuition. Today, I still offer my writing services to students.

    Professional Writer – Raiden Cantrell – studentenkamerbrugge.com Band

Leave a comment

 Comment Form