首页>Program>source

我有一个允许用户上传图片的表格。 用户提交表单后,我想在前端为每张图片生成缩略图,然后将其存储在服务器上。

出于安全原因,无法更改文件输入字段的值,那么如何将js前端生成的一些缩略图图像发送到服务器?

在提交表单之前,前端是否可以从输入文件字段中设置的图像生成缩略图? 然后同时提交两个?

最新回答
  • 1月前
    1 #

    我发现了这个更简单但功能强大的教程.它只是创建一个 img 元素,并使用fileReader对象将其source属性分配为输入形式的值

    function previewFile() {
      var preview = document.querySelector('img');
      var file    = document.querySelector('input[type=file]').files[0];
      var reader  = new FileReader();
      reader.onloadend = function () {
        preview.src = reader.result;
      }
      if (file) {
        reader.readAsDataURL(file);
      } else {
        preview.src = "";
      }
    }
    
    <input type="file" onchange="previewFile()"><br>
    <img src="" height="200" alt="Image preview...">
    

  • 1月前
    2 #

    经过更好的在线搜索,我找到了问题的答案。

    可以结合 canvasFile API一起

    尝试在下面的演示中上传任何图片,并查看新生成的缩略图会出现在表单的右侧。

    DEMO: http://jsfiddle.net/a_incarnati/fua75hpv/

    function handleImage(e){
        var reader = new FileReader();
        reader.onload = function(event){
            var img = new Image();
            img.onload = function(){
                canvas.width = img.width;
                canvas.height = img.height;
                ctx.drawImage(img,0,0);
            }
            img.src = event.target.result;
        }
        reader.readAsDataURL(e.target.files[0]);     
    }
    

    DerekR对这个问题给出了很好的答案:

    如何将图像上传到HTML5画布

  • 1月前
    3 #

    TL; DR:请参见JSFiddle

    因为我想通过API上传图像并显示图像预览(实际上两件事相互融为一体),所以我想到了:

    (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);
    

    预览工作所需的两个元素是:

    <canvas id="image-preview"></canvas>
    <input type="file" data-input-file-preview="image-preview" data-map-to-model="image.file" />
    

    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;
    }
    
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
    <form data-ng-app="app" data-ng-controller="UploadImageController">
        <input data-ng-model="image.title" />
        <br />
        <canvas id="image-preview"></canvas>
        <br />
        <input type="file" data-input-file-preview="image-preview" data-map-to-model="image.file" />
        <br />
        <input type="submit" data-ng-click="send(image)" />
        
        <pre>{{sentData}}</pre>
    </form>
    

  • 1月前
    4 #

    认为应该添加更现代的答案并引用MDN web文档。

    您可以在输入元素上添加"更改"事件侦听器,然后通过 this.files访问文件列表来显示所选图像的缩略图。 (如MDN示例中所示).这是我的最新实现. uploadwatermark是一个 <input type="file></input>

    uploadWatermark.addEventListener('change', function(){
      const file = this.files[0];
      if (file.type.startsWith('image/')) {
        const img = document.createElement('img');
        const watermarkPreview = document.getElementById("uploaded-watermark");
        img.classList.add("prev-thumb");
        img.file = file;
        watermarkPreview.appendChild(img);
        const reader = new FileReader();
        reader.onload = (function(aImg) { return function(e) { aImg.src =   e.target.result; }})(img);
        reader.readAsDataURL(file);
      }
      
    });
    

  • 32bit 64bit:作为程序员,转移到64位windows时我需要担心什么?
  • 从python使用Java库