Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I return a file from Controller to view?

I'm trying to return a file from controller to view (more specific a .jpeg) and not the path because I don't want to be seen.

This is my code at the moment:

sub get_avatar {
    my $self = shift;
    my $username = $self->stash('id');
    my $home = Mojo::Home->new;
    $home->detect('SuperSecret');
    my $path = $home->child('my', 'path', "$username");
    my $file;
    if (-e $path) {
    $file = "my/path/$username";
    } else {
    $file = "my/path/default.png";
    }
    return $file;
}

enter image description here

like image 654
Marinescu Avatar asked Nov 23 '25 22:11

Marinescu


1 Answers

The image can be encoded to pass it as a Data URL rather than linking to the file. See the example below of a simple application encoding an image.

#!/usr/bin/env perl
use Mojolicious::Lite;
use English;
use MIME::Base64;

my $filename = "acorn_PNG37023.png";
## read file as binary data
open( my $png_fh, '<:raw', $filename ) or die "$OS_ERROR";
read $png_fh, my $png_bin_data, -s $png_fh;
close($png_fh);

my $encoded = MIME::Base64::encode($png_bin_data);

get '/' => { 
    text => '<img src="data:image/png;base64,' . $encoded . '" alt="png" />'  
};

app->start;
like image 173
hoffmeister Avatar answered Nov 25 '25 15:11

hoffmeister