【问题标题】:prevent image uploading if oversize如果尺寸过大,请阻止图片上传
【发布时间】:2017-09-22 02:12:18
【问题描述】:

如果超过设定的大小,我需要阻止图像上传,我的错误会起作用并显示图像是否超过设定的大小但图像仍然会上传。 我正在使用angular-base64-upload

我不知道为什么图像超过限制时仍然显示,知道为什么吗?

谢谢

HTML

<div ng-controller="UpLoadImage">

<div ng-repeat="step in stepsModel">
    <img class="thumb" ng-src="{{step}}"/>
</div>

<label for="file">Add Creative</label>

<form name="form">
    <input type='file' ng-model='files' name='files' multiple accept='image/*, .zip' maxsize='50' onload='onLoad'
           ng-model-instant onchange='angular.element(this).scope().imageUpload(this)' required
           base-sixty-four-input>
    <span ng-show='form.files.$error.maxsize'>Files must not exceed 50 KB</span>
</form>

App.js

angular.module('myApp', ['naif.base64'])
.controller('UpLoadImage', function ($scope, $http, $window, $rootScope) {

    $scope.imageUpload = function (element) {
        var reader = new FileReader();
        reader.onload = $scope.imageIsLoaded;
        reader.readAsDataURL(element.files[0]);
    };

    $scope.imageIsLoaded = function (e) {
        $scope.$apply(function () {
            $scope.stepsModel.push(e.target.result);
        });

        $scope.onLoad = function (e, reader, file, fileList, fileOjects, fileObj) {
            alert('image uploaded');
        };
    };

    $scope.stepsModel = [];
})

【问题讨论】:

    标签: javascript angularjs npm


    【解决方案1】:

    您的 input 正在侦听 onchange 事件以进行上传 - 没有什么可以阻止此更改事件继续进行。

    form.files.$error.maxsize 将返回 truefalse,因此使用该布尔值来驱动更改事件是否继续进行上传尝试。

    我建议将您的上传逻辑移到您的控制器中。

    另外,如果您使用ng-change,您可以缩短对控制器方法的引用:

    ng-change="imageUpload(this, form.files.$error.maxsize)"

    如果您扩展 imageUpload 方法以获取第二个参数,您可以检查图像是否太大而无法继续:

    $scope.imageUpload = function (element, maxSizeError) {
    
        if(maxSizeError) { 
            // handle error logic
         } else {
            var reader = new FileReader();
            reader.onload = $scope.imageIsLoaded;
            reader.readAsDataURL(element.files[0]);
         }
    };
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2023-03-24
      • 1970-01-01
      • 1970-01-01
      • 2012-11-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多