- 论坛徽章:
- 0
|
本帖最后由 maybenot 于 2017-06-13 07:04 编辑
服务器端:(Cookbook上的例子)
- use Mojolicious::Lite;
- use Scalar::Util 'weaken';
- # Intercept multipart uploads and log each chunk received
- hook after_build_tx => sub {
- my $tx = shift;
- # Subscribe to "upgrade" event to identify multipart uploads
- weaken $tx;
- $tx->req->content->on(upgrade => sub {
- my ($single, $multi) = @_;
- return unless $tx->req->url->path->contains('/upload');
- # Subscribe to "part" event to find the right one
- $multi->on(part => sub {
- my ($multi, $single) = @_;
- # Subscribe to "body" event of part to make sure we have all headers
- $single->on(body => sub {
- my $single = shift;
- # Make sure we have the right part and replace "read" event
- return unless $single->headers->content_disposition =~ /example/;
- $single->unsubscribe('read')->on(read => sub {
- my ($single, $bytes) = @_;
- # Log size of every chunk we receive
- app->log->debug(length($bytes) . ' bytes uploaded');
- });
- });
- });
- });
- };
- # Upload form in DATA section
- get '/' => 'index';
- # Streaming multipart upload
- post '/upload' => sub {
- my $c = shift;
- my @files;
- for my $file ($c->req->upload('example')) {
- push @files, $file->filename;
- }
- $c->render(text => "file names:\n@files");
- };
- app->start;
- __DATA__
- @@ index.html.ep
- <!DOCTYPE html>
- <html>
- <head><title>Streaming multipart upload</title></head>
- <body>
- %= form_for upload => (enctype => 'multipart/form-data') => begin
- %= file_field 'example'
- %= submit_button 'Upload'
- % end
- </body>
- </html>
复制代码
然后用UserAgent上传文件:
- use Mojo::UserAgent;
- my $url = "http://127.0.0.1:3000/upload";
- my $ua = Mojo::UserAgent->new();
- my $tx = $ua->build_tx(POST => $url=> form => {example => { file=>'D:/report_data2.txt' }});
- $tx->req->on(progress => sub {
- my $msg = shift;
- return unless my $len = $msg->headers->content_length;
- my $size = $msg->content->progress;
- say 'Progress: ', $size == $len ? 100 : int($size / ($len / 100)), '%';
- });
- $tx = $ua->start($tx);
- print $tx->res->body;
复制代码 UA端代码我是参照的这里http://www.yishuiyixu.com/article/115
仅仅把$tx->res改成了$tx->req,文件上传成功并返回文件名没问题,就是进度信息不对,打印出很多0%
还请指点!
|
|