Anonymous Monk has asked for the wisdom of the Perl Monks concerning the following question:

Hi Monks!
I am trying to uplaod some pics from urls and I am getting an error on the "read(" in hte OPEN part of the code, I cant figure this one, can anyone take a look and tell why the read is not working, here is the error:
Software error: Read failure at test.pl

Here is the code:
#!/usr/bin/perl -w use strict; use CGI qw(-oldstyle_urls :standard); use CGI::Carp qw(fatalsToBrowser); use LWP::UserAgent; use URI::URL; use HTTP::Request; use Image::Size; my $num_bytes = 1024; my $totalbytes; my ($bytesread,$buffer); my $img = ""; my @the_url = ('http://www.test.com/images/one.jpg', 'http://www.test.com/images/two.jpg', 'http://www.test.com/images/three.jpg', 'http://www.test.com/images/four.jpg',); my $hdrs = new HTTP::Headers(Accept => 'text/plain', UserAgent =>'Mega +Browser/1.0'); my ($url,$req,$ua,$resp); print header(); my $c=0; foreach my $urls(@the_url) { $c++; my @full_url = split(/(\\)|(\/)/,$urls); my $filename = pop(@full_url); $filename =~ s/\n//; $filename =~ s/\r//; $filename = "andrey"."_".$filename; $filename=lc($filename); $url = new URI::URL($urls); $req = new HTTP::Request('GET', $url, $hdrs); $ua = new LWP::UserAgent; $resp = $ua->request($req); if ($resp->is_success) { $img = $resp->content; open(IMAGE, ">../../img/$filename") or die "$!"; binmode IMAGE; while ($bytesread = read($img,$buffer,$num_bytes)) { $totalbytes += $bytesread; print IMAGE $buffer; } die "Read failure" unless defined($bytesread); close IMAGE or die "$!"; } } print "<br>Done<br>";

Thanks for Help!

Replies are listed 'Best First'.
Re: FIle Upload Error Help!
by JavaFan (Canon) on Jul 21, 2011 at 18:55 UTC
    The first argument of read should be a file handle. You give a string as first argument.
      But at this point in read if I use the file handle it will have no value because the image file is in $img</cope> and not in the <code>$filename variable. How would you do it?
        I've no idea what is in $img, other than it's a string. Perhaps all you want is:
        $url = new URI::URL($urls); $req = new HTTP::Request('GET', $url, $hdrs); $ua = new LWP::UserAgent; $resp = $ua->request($req); if ($resp->is_success) { open(IMAGE, ">../../img/$filename") or die "$!"; binmode IMAGE; print IMAGE $resp->content; }
        But then you may want to use LWP::Simple instead.