brandonsavage / Upload

File uploads with validation and storage strategies
MIT License
1.67k stars 315 forks source link

Html Canvas & Javascript FileReader #107

Open mategvo opened 7 years ago

mategvo commented 7 years ago

Hi, I have somewhat modern implementation of the file upload. It combines "croppie", a tool that allows a user to move and crop the image, and Javascript FileReader feature. Result is POSTed to the PHP API as an encoded string:

data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAJ4AA...

Unfortunately the Upload library doesn't recognise this format.

Cannot find uploaded file identified by key: image
codeguy/upload/src/Upload/File.php

Is there a way around this?

mategvo commented 7 years ago

Here's the full code, maybe someone will find it useful

    <form method="post" enctype="multipart/form-data" id="groupImageForm">
        <link  href="css/croppie.css" rel="stylesheet">
        <script src="js/croppie.min.js"></script>
        <div id="upload-demo"></div>
        <input type="hidden" id="imagebase64" name="image">
        <input type="file" id="upload" value="Choose a file">
        <a href="#" class="upload-result">Send</a>
        <script type="text/javascript">
        $( document ).ready(function() {
            var $uploadCrop;

            function readFile(input) {
                if (input.files && input.files[0]) {
                    var reader = new FileReader();
                    reader.onload = function (e) {
                        $uploadCrop.croppie('bind', {
                            url: e.target.result
                        });
                        $('.upload-demo').addClass('ready');
                    }
                    reader.readAsDataURL(input.files[0]);
                }
            }

            $uploadCrop = $('#upload-demo').croppie({
                viewport: {
                    width: 200,
                    height: 200,
                    type: 'circle'
                },
                boundary: {
                    width: 300,
                    height: 300
                }
            });

            $('#upload').on('change', function () { readFile(this); });
            $('.upload-result').on('click', function (ev) {
                $uploadCrop.croppie('result', {
                    type: 'canvas',
                    size: 'original'
                }).then(function (resp) {
                    $('#imagebase64').val(resp);
                    $('#groupImageForm').submit();
                });
            });

        });
        </script>
    </form>