Search code examples
javascriptng-file-upload

NgfileUpload - How to apply validation one each file while sending them all in one request


This is an already made fiddle for multiple file in one request Fiddle. Now I want to have a validation in which no file should be greater than 1MB . How can I do this ? How can I through error on each file. ?


Solution

  • You can iterate through each of the files and check their size and then show whatever error you want. I simply set the error message here but you can do something else.

    //inject angular file upload directives and services.
    var app = angular.module('fileUpload', ['ngFileUpload']);
    
    app.controller('MyCtrl', ['$scope', 'Upload', '$timeout', function ($scope, Upload, $timeout) {
        $scope.uploadFiles = function (files) {
            $scope.files = files;
            if (files && files.length) {
                if (!files.every(function(file) {
                  return file.size < 1;
                })) {
                   return $scope.errorMsg = 'File size too big';
                };
                Upload.upload({
                    url: 'https://angular-file-upload-cors-srv.appspot.com/upload',
                    data: {
                        files: files
                    }
                }).then(function (response) {
                    $timeout(function () {
                        $scope.result = response.data;
                    });
                }, function (response) {
                    if (response.status > 0) {
                        $scope.errorMsg = response.status + ': ' + response.data;
                    }
                }, function (evt) {
                    $scope.progress = 
                        Math.min(100, parseInt(100.0 * evt.loaded / evt.total));
                });
            }
        };
    }]);
    

    http://jsfiddle.net/huhjo9jm/756/