Web Template – Upload to Image column on existing record

<!-- Check a GUID has been provided in the URL -->
{% if request.params.id.size == 36 %}
    <!-- Retrieve the track record by GUID -->
    {% assign track_record = entities['musdyn_track'][request.params.id] %}
        {% if track_record %}
            <!-- Include the Portal Web API Wrapper web template to get an authentication token -->
            {% include 'Portal Web API Wrapper' %}
            <div class="container">
                <div class="col-md-6 col-sm-12">
                    <!-- This div is shown by default but will be hidden if the upload succeeds -->
                    <div class="hideOnSuccess">
                        <h1>Existing Artwork</h1>
                        <!-- If the artwork field is not populated, show the placeholder / not found image -->
                        {% unless track_record.musdyn_artworkid %}
                            <img id="existing-artwork" src="/artwork-not-found.svg" style="width:300px; height: auto;" />
                        {% else %}
                            <img id="existing-artwork" style="width:300px; height: auto;" />
                        {% endunless %}
                    </div>
                    <!-- This div is hidden by default but will be shown if the upload succeeds -->
                    <div class="showOnSuccess" style="display:none;">
                        <h1>Your New Artwork</h1>
                        <img id="uploaded-artwork" style="width:300px; height: auto;" />
                    </div>
                </div>
                <div class="col-md-6 col-sm-12">
                    <h1>Upload Artwork</h1>
                        <!-- A form to upload to images, retricted to accept only JPGs, GIF, TIFFs or PNGs -->
                        <form id="image-upload">
                            <input id="artworkDocumentbody" accept="image/jpg,image/jpeg,image/gif,image/tif,image/tiff,image/png" type="file">
                            <a class="btn btn-default" id="submitArtwork" href="#">Upload</a>
                        </form>
                        <!-- This bootstrap alert is hidden by default but will be shown if an error is encountered with the upload -->
                        <div class="alert alert-danger showOnError" role="alert" style="display:none;"><span class="glyphicon glyphicon-warning-sign" aria-hidden="true"></span> Upload failed. Please try again</div>
                </div>
            </div>

            <!-- If the track record has existing artwork -->
            {% if track_record.musdyn_artworkid %}
            <script>
                // When the page loads, get the existing artwork for this Track record
                $( document ).ready(function() {
                    webapi.safeAjax({
                        type: "GET",
                        url: "/_api/musdyn_tracks({{request.params.id}})/musdyn_artwork",
                        contentType:"application/json",
                        success: function(res) {
                            // If successful, set the source of the existing artwork image to the retrieved file
                            $('img#existing-artwork').attr('src','data:image/png;base64,' + res.value);
                        },
                        error: function(xhr, status, error){
                            // If error, log to the console
                            var errorMessage = xhr.status + ': ' + xhr.statusText;
                            console.log(errorMessage);
                        }
                    });
                });
            </script>
            {% endif %}

            <script>
            // When the submitArtwork link is clicked
            $( '#submitArtwork' ).click(function(e) {
                // Run the getImageFileContents function
                getImageFileContents();
                // Don't perform the default behaviour for the link i.e. navigation
                e.preventDefault();                
            });

            function getImageFileContents() {
                // Get the content of the selected file
                var file = document.getElementById('artworkDocumentbody').files[0];
                // If the user has selected a file
                if (file) {
                    // Read the file
                    var reader = new FileReader();
                    reader.readAsDataURL(file);
                    // The browser has finished reading the file, we can now do something with it...
                    reader.onload = function(e) {
                        // The browser has finished reading the file, we can now do something with it...
                        var artworkDocumentbodyContents = e.target.result;
                        // Split the string at the first comma (removing the base64 prefix)
                        artworkDocumentbodyContents = artworkDocumentbodyContents.substring(artworkDocumentbodyContents.indexOf(',')+1);
                        // Run the function to upload to the Portal Web API, passing the file's contents as an input
                        uploadToImageColumn(artworkDocumentbodyContents);
                    };
                }
            }
            function uploadToImageColumn(artworkDocumentbodyContents) {
                // Provide visual feedback that the upload function has started (changing the button text)
                $('#submitArtwork').html('Uploading...');

                webapi.safeAjax({
                    type: "PUT",
                    url: "/_api/musdyn_tracks({{request.params.id}})/musdyn_artwork",
                    contentType:"application/json",
                    data: JSON.stringify({
                        "value":artworkDocumentbodyContents
                    }),
                    // On success
                    success: function() {
                        // Provide visual feedback that the upload function has started (changing the button text to a tick / check mark)
                        $('#submitArtwork').html('<span class="glyphicon glyphicon-ok"></span>');
                        // Show the new artwork by setting the source of the 'uploaded artwork' image
                        $('img#uploaded-artwork').attr('src','data:image/jpeg;base64,' + artworkDocumentbodyContents);
                        // Hide any elements with the 'hideOnSuccess' class
                        $('div.hideOnSuccess').slideToggle();
                        // Show any elements with the 'showOnSuccess' class
                        $('div.showOnSuccess').slideToggle();
                        // Hide any elements with the 'showOnError' class
                        $('.showOnError').hide();
                    },
                    // On error
                    error: function(xhr, status, error){
                        // Change the text on the upload link back from 'Uploading...' to 'Upload'
                        $('#submitArtwork').html('Upload');
                        // Hide any elements with the 'hideOnError' class
                        $('.showOnError').show();
                        // Log the error detais to the console
                        var errorMessage = xhr.status + ': ' + xhr.statusText;
                        console.log(errorMessage);
                    }
                });
            }

            </script>
        {% endif %}
    {% else %}
    <!-- if the track record is not found, display a bootstrap alert -->
    <div class="container">
        <div class="alert alert-danger" role="alert">
            <span class="glyphicon glyphicon-warning-sign" aria-hidden="true"></span> Track record not found / no unique identifier provided in the URL. I don't know which track to upload artwork to
        </div>
    </div>
{% endif %}
Franco Musso