如何使用Mojolicious上传多个文件?

时间:2015-02-19 09:37:55

标签: perl mojolicious

我是Mojolicious的新手,试图学习它。我尝试使用表单上传多个文件,但一次只上传一个文件。有什么建议吗?

#!perl -w

use Mojolicious::Lite;
use Mojo::Upload;
use v5.14;

get '/' => 'page';
post '/' => sub {
   my $self = shift;
   my @files;
   for my $file ($self->req->upload('files')) {
     my $size = $file->size;
     my $name = $file->filename;

     push @files, "$name ($size)";
     $file->move_to("C:\\Program Files\\Apache Software Foundation\\Apache24\\htdocs\\ProcessingFolder\\".$name);
   }
   $self->render(text => "@files");
} => 'save';

app->start;

__DATA__

@@ page.html.ep
<!DOCTYPE html>
<html>
   <body>
   <form action="<%=/ProcessingFolder/%>" method="POST"
enctype="multipart/form-data">
     <input name="files" type="file" enctype="multipart/form-data" multiple="multiple">
     <button type="submit">Upload</button>
   </form>
   </body>
</html>

2 个答案:

答案 0 :(得分:2)

找到答案。使用uploads()而不是返回数组引用的upload()

#!perl -w

use Mojolicious::Lite;
use Mojo::Upload;
use v5.14;

get '/' => 'page';
post '/' => sub {
   my $self = shift;
   my @files;
   for my $file (@{$self->req->uploads('files')}) {
     my $size = $file->size;
     my $name = $file->filename;

     push @files, "$name ($size)";
     $file->move_to("C:\\Program Files\\Apache Software Foundation\\Apache24\\htdocs\\ProcessingFolder\\".$name);
   }
   $self->render(text => "@files");
} => 'save';

app->start;

__DATA__

@@ page.html.ep
<!DOCTYPE html>
<html>
   <body>
   <form action="<%=/ProcessingFolder/%>" method="POST"
enctype="multipart/form-data">
     <input name="files" type="file" enctype="multipart/form-data" multiple="multiple">
     <button type="submit">Upload</button>
   </form>
   </body>
</html>

答案 1 :(得分:1)

我认为answer above 中有一个小错误-变量ProcessingFolder已过时...

#!perl -w
# install Mojolicious by : sudo -s 'curl -L cpanmin.us | perl - Mojolicious'
# run by : perl mojo-file-upload.pl daemon -m production -l http://*:8083
# point your browser @: http://127.0.0.1/upload-files
#
use Mojolicious::Lite;
use Mojo::Upload;
use v5.14;

get '/' => 'upload-files-page';
get '/upload-files' => 'upload-files-page';
post '/upload-files' => sub {
   my $self = shift;
   my @files;
   for my $file (@{$self->req->uploads('files')}) {
     my $size = $file->size;
     my $name = $file->filename;

     push @files, "$name ($size)";
     $file->move_to("/tmp/".$name);
   }
   $self->render(text => "@files");
} => 'save';

app->start;

__DATA__


@@ upload-files-page.html.ep
<!DOCTYPE html>
<html>
   <body>
   <form action="/upload-files" method="POST"
enctype="multipart/form-data">
     <input name="files" type="file" 
       enctype="multipart/form-data" multiple="multiple">
     <button type="submit">Upload</button>
   </form>
   </body>
</html>