How to generate a thumbnail image after adding an image inside an input type=“file” in a form and submitting them both on the same form

后端 未结 5 971
误落风尘
误落风尘 2020-11-30 19:58

I have a form which allows the user to upload a picture. After the user has submitted the form, I\'d like to generate on the front-end a thumbnail for each picture and then

5条回答
  •  爱一瞬间的悲伤
    2020-11-30 20:15

    TL;DR: See the JSFiddle

    As I wanted to upload images via an API and show a preview of the image (two things that actually lended themselves well to each other), I came up with this:

    (function(angular) {
        angular
            .module('app')
            .directive('inputFilePreview', [function() {
    
                var canvas, mapToModel, elementScope;
    
                /**
                 * To be fired when the image has been loaded
                 */
                var imageOnLoad = function(){
                    canvas.width = this.width;
                    canvas.height = this.height;
                    canvas.getContext("2d").drawImage(this,0,0);
                };
    
                /**
                 * To be fired when the FileReader has loaded
                 * @param loadEvent {{}}
                 */
                var readerOnLoad = function(loadEvent){
                    var img = new Image();
                    img.onload = imageOnLoad;
                    img.src = loadEvent.target.result;
                    if(mapToModel) {
                        setModelValue(elementScope, mapToModel, img.src);
                    }
                };
    
                /**
                 * This allows us to set the value of a model in the scope of the element (or global scope if the
                 * model is an object)
                 * @param scope {{}}
                 * @param modelReference {string}
                 * @param value {*}
                 */
                var setModelValue = function(scope, modelReference, value) {
                    // If the model reference refers to the propery of an object (eg. "object.property")
                    if(~modelReference.indexOf('.')) {
                        var parts = modelReference.split('.', 2);
                        // Only set the value if that object already exists
                        if(scope.hasOwnProperty(parts[0])) {
                            scope[parts[0]][parts[1]] = value;
                            return;
                        }
                    }
                    scope[modelReference] = value;
                };
    
                /**
                 * The logic for our directive
                 * @param scope {{}}
                 * @param element {{}}
                 * @param attributes {{}}
                 */
                var link = function(scope, element, attributes) {
                    elementScope = scope;
                    canvas = document.getElementById(attributes.inputFilePreview);
                    if(attributes.hasOwnProperty('mapToModel')) {
                        mapToModel = attributes.mapToModel;
                    }
                    element.on('change', function(changeEvent) {
                        var reader = new FileReader();
                        reader.onload = readerOnLoad;
                        reader.readAsDataURL(changeEvent.target.files[0]);
                    });
                };
    
                return {
                    restrict: 'A',
                    link: link
                };
            }]);
    })(angular);
    

    The two elements needed for the preview to work are:

    
    
    

    Snippet Follows:

    (function (angular) {
        angular.module('app', [])
            .directive('inputFilePreview', [function () {
    
            var canvas, mapToModel, elementScope;
    
            /**
             * To be fired when the image has been loaded
             */
            var imageOnLoad = function () {
                canvas.width = this.width;
                canvas.height = this.height;
                canvas.getContext("2d").drawImage(this, 0, 0);
            };
    
            /**
             * To be fired when the FileReader has loaded
             * @param loadEvent {{}}
             */
            var readerOnLoad = function (loadEvent) {
                var img = new Image();
                img.onload = imageOnLoad;
                img.src = loadEvent.target.result;
                if (mapToModel) {
                    setModelValue(elementScope, mapToModel, img.src);
                }
            };
    
            /**
             * This allows us to set the value of a model in the scope of the element (or global scope if the
             * model is an object)
             * @param scope {{}}
             * @param modelReference {string}
             * @param value {*}
             */
            var setModelValue = function (scope, modelReference, value) {
                // If the model reference refers to the propery of an object (eg. "object.property")
                if (~modelReference.indexOf('.')) {
                    var parts = modelReference.split('.', 2);
                    // Only set the value if that object already exists
                    if (scope.hasOwnProperty(parts[0])) {
                        scope[parts[0]][parts[1]] = value;
                        return;
                    }
                }
                scope[modelReference] = value;
            };
    
            /**
             * The logic for our directive
             * @param scope {{}}
             * @param element {{}}
             * @param attributes {{}}
             */
            var link = function (scope, element, attributes) {
                elementScope = scope;
                canvas = document.getElementById(attributes.inputFilePreview);
                if (attributes.hasOwnProperty('mapToModel')) {
                    mapToModel = attributes.mapToModel;
                }
                element.on('change', function (changeEvent) {
                    var reader = new FileReader();
                    reader.onload = readerOnLoad;
                    reader.readAsDataURL(changeEvent.target.files[0]);
                });
            };
    
            return {
                restrict: 'A',
                link: link
            };
        }])
            .controller('UploadImageController', [
            '$scope',
    
        function ($scope) {
    
            $scope.image = {
                title: 'Test title'
            };
    
            $scope.send = function (data) {
                $scope.sentData = JSON.stringify(data, null, 2);
                return false;
            };
        }]);
    })(angular);
    canvas {
        max-height: 300px;
        max-width: 300px;
    }
    
    



    {{sentData}}

提交回复
热议问题