CGI::Application::Plugin::Stream - CGI::Application Plugin for streaming files


  use CGI::Application::Plugin::Stream (qw/stream_file/);

  sub runmode {
    # ...

    # Set up any headers you want to set explicitly
    # using header_props() or header_add() as usual


    if ( $self->stream_file( $file ) ) {
    } else {
      return $self->error_mode();


This plugin provides a way to stream a file back to the user.

This is useful if you are creating a PDF or Spreadsheet document dynamically to deliver to the user.

The file is read and printed in small chunks to keep memory consumption down.

This plugin is a consumer, as in your runmode shouldn't try to do any output or anything afterwards. This plugin affects the HTTP response headers, so anything you do afterwards will probably not work. If you pass along a filehandle, we'll make sure to close it for you.

It's recommended that you increment $| (or set it to 1), which will autoflush the buffer as your application is streaming out the file.



  $self->stream_file( '/path/to/file',2048);

This method can take two parameters, the first the path to the file or a filehandle and the second, an optional number of bytes to determine the chunk size of the stream. It defaults to 1024.

It will either stream a file to the user or return false if it fails, perhaps because it couldn't find the file you referenced.

We highly recommend you provide a file name if passing along a filehandle, as we won't be able to deduce the file name, and will use 'FILE' by default. Example:

 $self->header_add( -attachment => 'my_file.txt' );

With both a file handle or file name, we will try to determine the correct content type by using File::MMagic. A default of 'application/octet-stream' will be used if File::MMagic can't figure it out.

The size will be calculated and added to the headers as well.

Again, you can set these explicitly if you want as well:

      -type                     =>      'text/plain',
      -Content_Length   =>      42, # bytes


Jason Purdy, <Jason@Purdy.INFO>, with inspiration from Tobias Henoeckl and tremendous support from the cgiapp mailing list.

Mark Stosberg also contributed to this module.


CGI::Application,, "CREATING A STANDARD HTTP HEADER" in,, File::Basename, "$|" in perlvar


Copyright (C) 2004-2005 Jason Purdy, <Jason@Purdy.INFO>

This library is free software. You can modify and or distribute it under the same terms as Perl itself.