SASBurns has asked for the wisdom of the Perl Monks concerning the following question:

Hi, I am using a Cropit.js to let my users customize their uploaded images but the problem is, it uses: data:image/png;base64,iVBORw0k... so what i did is i've used the MIME::Base64 Perl Module. So here's how i did it:
<!-- MY HTML FORM --> <form action="upload.pl" method="post" enctype="multipart/form-data"> <div class="image-editor"> <input type="file" class="cropit-image-input" /> <div class="cropit-preview"></div> <div class="image-size-label"> Resize Image: </div> <input type="range" class="cropit-image-zoom-input" /> <input type="hidden" name="imagedata" class="hidden-image-data" /> <button type="submit">save</button> </div> </form> <!-- END OF HTML FORM -->
Here's my Perl Code:
#!/usr/bin/perl use strict; use warnings; use CGI; use MIME::Base64; my $arg=new CGI; my $fetch_photo=$arg->param('imagedata'); my $decoded=MIME::Base64::decode_base64($fetch_photo); my $filename; $filename=int rand(1000).".png" if $fetch_photo=~/png/; $filename=int rand(1000).".jpg" if $fetch_photo=~/jpg/; open(FILE, ">img/$filename") or die 'err'; binmode FILE; print FILE $decoded; close(FILE);
It keeps uploading a unreadable/corrupted image file please help! thank you.

Replies are listed 'Best First'.
Re: uploading a data:image/imagetype,base64 in perl
by Mr. Muskrat (Canon) on Dec 04, 2017 at 20:14 UTC

    It looks like you need to remove 'data:image/png;base64,' from the beginning of $fetch_photo before you pass it into decode_base64.

    Update: Here's an updated script that improves upon how you were doing things. It passed cursory testing.

    #!/usr/bin/perl use strict; use warnings; use CGI; use MIME::Base64; my $arg = new CGI; my $fetch_photo = $arg->param('imagedata'); my ($data, $base64) = split /,/, $fetch_photo; my ($type) = $data =~ m!data:image/(\w+);base64!; my $decoded = MIME::Base64::decode_base64($base64); my $filename = int(rand(1000)) . '.' . $type; open(my $file, '>', "img/$filename") or die 'err'; # 3 argument open binmode $file; print $file $decoded; close($file);
Re: uploading a data:image/imagetype,base64 in perl
by Corion (Patriarch) on Dec 04, 2017 at 18:36 UTC

    Maybe there is some other data in front of the data you fetch from ->param('imagedata')?

    Maybe save the raw base64 data to a file first and have a look at it?

    MIME::Base64 doesn't document any kind of error handling, so I would look at the raw data coming in first.