Save content on the web as a file with Mojo::UserAgent
Let's get the file from the web with Mojo::UserAgent and save it. Write as follows.
use Mojo::UserAgent; my $ua = Mojo::UserAgent->new; my $file ='google.html'; my $url ='http://www.google.co.jp/'; $ua->get($url)->res->content->asset->move_to($file);
Mojo::UserAgent doesn't have a method to download, so you have to do your best on your own.
- Issue an HTTP request with the get method. The return value is a Mojo::Transaction::HTTP object.
- Get HTTP response with res method. The return value is a Mojo::Message::Request object.
- Get the content with the content method. The return value is a Mojo::Content::Single object.
- Get what the content actually has with the asset method. The return value is a Mojo::Asset::Memory object or a Mojo::Asset::File object.
- Save to a file with the move_to method.
It will be the flow. Is it a little complicated?
When saving a file from Test::Mojo.
When testing Mojolicious, you may want to download a file. In such a case, write as follows. I also included a description of the temporary directory.
use Test::Mojo;
use File::Temp'tempdir';
use YourApp;
my $app = YourApp->new;
my $t = Test::Mojo->new($app);
my $tmpdir = tempdir (CLEANUP => 1);
my $tmpfile = "$tmpdir / tmp.tar.gz";
$t->get_ok('http://somehost.com');
->tx->res->content->asset->move_to($tmpfile);
The mechanism is the same, except that the Mojo::Transaction::HTTP is obtained from Test::Mojo using the tx method.
Mojolicious Tutorial