Snippets

Brian Medley File upload shimmy

You are viewing an old version of this snippet. View the current version.
Revised by Brian Medley 87e7fb0
#!/opt/perl

use Mojolicious::Lite;

get '/' => 'form';

post '/' => sub {
    my $c = shift;

    my $url = Mojo::URL->new('http://127.0.0.1:3001/upload');
    
    $c->redirect_to('http://127.0.0.1:3001/upload');
};

post '/upload' => sub {
  my $c = shift;

  # Check file size
  return $c->render(text => 'File is too big.', status => 200)
    if $c->req->is_limit_exceeded;

  # Process uploaded file
  return $c->redirect_to('form') unless my $example = $c->param('example');
  my $size = $example->size;
  my $name = $example->filename;
  $c->render(text => "Thanks for uploading $size byte file $name.");
};

my $mode = shift(@ARGV);
push(@ARGV, "daemon", "-l", 'http://*:3000') if "redirect" eq $mode;
push(@ARGV, "daemon", "-l", 'http://*:3001') if "process" eq $mode;

app->start;

__DATA__

@@ form.html.ep
<!DOCTYPE html>
<html>
  <head><title>Upload</title></head>
  <body>
    %= form_for '/' => (enctype => 'multipart/form-data', method => 'POST') => begin
      %= file_field 'example'
      %= submit_button 'Upload'
    % end
  </body>
</html>
HTTPS SSH

You can clone a snippet to your computer for local editing. Learn more.