FAQ

[html-formfu] [Proposed patch] By-extension MIME type guess for H::F::Constraint::File::MIME

Michele Beltrame
Aug 18, 2009 at 10:37 am
Hi!

Attached is a patch which add the option to pass a "byextension"
parameter to the HTML::FormFu::Constraint::File::MIME which causes the
MIME type to be computed on the server (depending on file extension)
instead of relying on the one passed by the browser. This is sometimes
more reliable, in my experience.

The patch is backward compatible: if no "byextension" parameter is set,
the MIME type provided by the client will be used.

I can add some tests, refine the docs and commit it to the repository if
it seems OK to do that.

Thanks,
Michele.

--
Michele Beltrame
http://www.italpro.net/ - mb@italpro.net
SkyPe: arthas77 - Twitter: mbeltrame
-------------- next part --------------
--- home/mb/devel/html-formfu/HTML-FormFu/lib/HTML/FormFu/Constraint/File/MIME.pm
+++ u/www/SAN/San/lib/HTML/FormFu/Constraint/File/MIME.pm
@@ -5,8 +5,9 @@

use List::MoreUtils qw( any );
use Scalar::Util qw( blessed );
+use MIME::Types;

-__PACKAGE__->mk_item_accessors(qw( regex ));
+__PACKAGE__->mk_item_accessors(qw( regex byextension ));

__PACKAGE__->mk_accessors(qw( types ));

@@ -17,7 +18,7 @@

return if !blessed($value) || !$value->isa('HTML::FormFu::Upload');

- my $input = $value->headers->content_type;
+ my $input = $self->_get_input_type($value);
my $types = $self->types;
my $regex = $self->regex;

@@ -34,6 +35,22 @@
}

return;
+}
+
+# Get the content type of the input, which could be computer
+# locally depending on the file extension or be the one passed
+# by the browser, depending on user choice
+sub _get_input_type {
+ my ( $self, $value ) = @_;
+
+ if ( $self->byextension ) {
+ my $mimet = MIME::Types->new();
+ # No extension, return undefined
+ return if $value->filename !~ m/ \. (\w+?) \z/xms;
+ return $mimet->mimeTypeOf(lc $1);
+ }
+
+ return $value->headers->content_type;
}

1;
@@ -76,6 +93,23 @@
The regex uses the C</x> flag, so that whitespace in the given string is
ignored.

+=head2 byextension
+
+Arguments: 0 or 1 (or any positive value)
+
+Default: 0
+
+Optional.
+
+If set to a positive value, uses the file extension to locally
+compute the MIME type of the file. This can be useful as not all
+clients pass the correct content-type (some, for instance, pass
+text/html for everything - sik!).
+
+Using extensions to calculate MIME types can, however, be less
+robust, so choose wisely what to do. See L<MIME::Types> documentation
+for details.
+
=head1 SEE ALSO

Is a sub-class of, and inherits methods from L<HTML::FormFu::Constraint>
reply

Search Discussions

Discussion Posts

Follow ups

Related Discussions

Discussion Navigation
viewthread | post
posts ‹ prev | 1 of 2 | next ›

1 user in discussion

Michele Beltrame: 2 posts