From 4d6e7659706445947795fa5319a0d988e8cbff49 Mon Sep 17 00:00:00 2001 From: Moritz Bunkus Date: Mon, 7 Mar 2011 13:19:38 +0100 Subject: [PATCH] Funktion "send_file" im Controller, um Dateien herunterzuladen --- SL/Controller/Base.pm | 32 ++++++++++++++++++++++++++++++++ SL/Form.pm | 2 ++ 2 files changed, 34 insertions(+) diff --git a/SL/Controller/Base.pm b/SL/Controller/Base.pm index d80fca16d..d50d519b7 100644 --- a/SL/Controller/Base.pm +++ b/SL/Controller/Base.pm @@ -5,6 +5,7 @@ use strict; use parent qw(Rose::Object); use Carp; +use IO::File; use List::Util qw(first); # @@ -83,6 +84,22 @@ sub render { return $output; } +sub send_file { + my ($self, $file_name, %params) = @_; + + my $file = IO::File->new($file_name, 'r') || croak("Cannot open file '${file_name}'"); + my $content_type = $params{type} || 'application/octet_stream'; + my $attachment_name = $params{name} || $file_name; + $attachment_name =~ s:.*//::g; + + print $::form->create_http_response(content_type => $content_type, + content_disposition => 'attachment; filename="' . $attachment_name . '"', + content_length => -s $file); + + $::locale->with_raw_io(\*STDOUT, sub { print while <$file> }); + $file->close; +} + # # Before/after run hooks # @@ -368,6 +385,21 @@ browser. Typical use for actions called via AJAX: $self->render('todo/single_item', { type => 'js' }, item => $employee->most_important_todo_item); +=item C + +Sends the file C<$file_name> to the browser including appropriate HTTP +headers for a download. C<%params> can include the following: + +=over 2 + +=item * C -- the file's content type; defaults to +'application/octet_stream' + +=item * C -- the name presented to the browser; defaults to +C<$file_name> + +=back + =item C =item C diff --git a/SL/Form.pm b/SL/Form.pm index b2cb1dead..1a2573960 100644 --- a/SL/Form.pm +++ b/SL/Form.pm @@ -629,6 +629,8 @@ sub create_http_response { $cgi_params{'-charset'} = $params{charset} if ($params{charset}); $cgi_params{'-cookie'} = $session_cookie if ($session_cookie); + map { $cgi_params{'-' . $_} = $params{$_} if exists $params{$_} } qw(content_disposition content_length); + my $output = $cgi->header(%cgi_params); $main::lxdebug->leave_sub(); -- 2.20.1