[dancer-users] Outputting binary data

David Precious davidp at preshweb.co.uk
Wed Jan 2 10:45:19 GMT 2013


On Tue, 1 Jan 2013 18:17:28 +0000
Rik Brown <rik at rikbrown.co.uk> wrote:

> Hi all,  
> 
> If I've got a scalar $data containing some binary data (a JPG image
> read using read_file($file, binmode => ':raw' ), how can I cause one
> of my routes to output it?
> 
> I've done essentially this (simplified):
> 
> get '/some/route' => sub {
>   my $data = …get_image…;
> 
>   header 'Content-Type' => 'image/jpeg';
>   return $data;
> }
> 
> but this doesn't feel right and causes a broken output (appears to
> return only a few rows of pixels of the image).   

That's acceptable enough, and should work (and, according to your
subsequent reply, does after fixing some problem with reading the
image).

If it's a simple as sending the content of an image file, you probably
want to just let send_file() do it.

e.g. send_file($filename, content_type => "image/jpeg");

You can omit the content_type option if you want to, in which case a
reasonable guess will be made for you based on the filename.

The send_file() keyword also understands a scalar ref as content to
send, so you could equally say:

  send_file(\$image_data, 
      content_type => "image/jpeg",
      filename     => "myimage.jpg",
  );



-- 
David Precious ("bigpresh") <davidp at preshweb.co.uk>
http://www.preshweb.co.uk/     www.preshweb.co.uk/twitter
www.preshweb.co.uk/linkedin    www.preshweb.co.uk/facebook
www.preshweb.co.uk/cpan        www.preshweb.co.uk/github




More information about the dancer-users mailing list