42

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

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

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

4

5 回答 5

65

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

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...">

于 2015-02-08T03:59:31.477 回答
23

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

可以将canvasFile API结合使用。

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

演示: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 画布中

于 2013-05-14T16:32:30.717 回答
11

建立在 Allesandro 写的更务实的东西之上。

该函数从 File API 中获取一个文件,并尝试将其放入 boundBox 中,同时保留纵横比。没有绘制任何内容,但是您会返回一个Promise吐出生成的 dataUrl 的内容。

// Creates a thumbnail fitted insize the boundBox (w x h)
generateThumbnail(file, boundBox){
  if (!boundBox || boundBox.length != 2){
    throw "You need to give the boundBox"
  }
  var scaleRatio = Math.min(...boundBox) / Math.max(file.width, file.height)
  var reader = new FileReader();
  var canvas = document.createElement("canvas")
  var ctx = canvas.getContext('2d');

  return new Promise((resolve, reject) => {
    reader.onload = function(event){
        var img = new Image();
        img.onload = function(){
            var scaleRatio = Math.min(...boundBox) / Math.max(img.width, img.height)
            let w = img.width*scaleRatio
            let h = img.height*scaleRatio
            canvas.width = w;
            canvas.height = h;
            ctx.drawImage(img, 0, 0, w, h);
            return resolve(canvas.toDataURL(file.type))
        }
        img.src = event.target.result;
    }
    reader.readAsDataURL(file);
  })
}

它可以像下面这样使用

generateThumbnail(file, [300, 300]).then(function(dataUrl){
    console.log(dataUrl)
})
于 2020-05-12T14:47:40.470 回答
1

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" />

片段如下:

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

于 2015-03-18T12:09:41.440 回答
1

认为添加一个更现代的答案并引用MDN Web Docs可能值得。

您可以在输入元素上为“更改”添加事件侦听器,然后通过访问文件列表来显示所选图像的缩略图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);
  }
  
});

于 2018-08-31T16:01:33.617 回答