Angularjs how to get filename extension?

Hi I am developing an angularjs application. I am making a file upload module. I am trying to check files. I only want to download xlsx or xls files. I designed a directive and a factory method for uploading files as shown below.

myapp.directive('fileModel', ['fileUploadExcel', function (fileUploadExcel) {
    return {
        restrict: 'A',
        link: function (scope, element, attrs) {
            element.bind("change", function (evt) {
                fileUploadExcel.pendingFiles[attrs.fileModel] = evt.target.files[0];
            });
        }
    };
}]);

      

Below is my controller.

 $scope.upload = function (filename) {
 fileUploadExcel.doUpload().success(function (success) {
 }).error(function (error) {
});

      

Below is my factory code.

myapp.factory('fileUploadExcel', ['$http', '$cookieStore', 'cfg', function ($http, $cookieStore, cfg) {
    var LoginID = $cookieStore.get("LoginID");
    var baseurl = cfg.Baseurl;
    var fileuploadurl = baseurl + 'api/Customer/BulkUploadVehicle/';

    var service = {
        uploadUrl: fileuploadurl,
        pendingFiles: {},
        doUpload: doUpload
    };
    return service;
    function doUpload() {
        var filename;
        var files = new FormData();
        files.append('LoginID', LoginID);
        angular.forEach(this.pendingFiles, function (value, index) {
            filename = value.name;
            files.append(index, value);
        });
        var extn = filename.split(".").pop();
        if (extn == 'xlsx' || extn == 'xls') {
            return $http.post(this.uploadUrl, files, {
                transformRequest: angular.identity,
                headers: {
                    'Content-Type': undefined
                }
            })
        }
        else
        {
            return false;
        } 
    }
}]);

      

I can get extn successfully. When my files are of type excel my code works fine. Whenever I download other than excel I get the error. I wrote return false. It doesn't work here. I have to return something else. May I know what I should write in another case? Can anyone help me here? Any help would be greatly appreciated. Thank.

+3


source to share


3 answers


You return a different type:

On success, you will return the $ http promise in your factory, so that you can call the success and error function in your controller with that:

fileUploadExcel.doUpload().success()

exist!

but if error, you are returning false in your factory, in this case it is a boolean and not a $ http promise, so you cannot use the success and error function.

fileUploadExcel.doUpload().success()

does not exist and returns an error



Of course, the solution is to check if the return value is not false and continue with your code, but I suggest always returning a promise, resolving it if successful and rejecting it on error , so the promise chain is not broken.

PS: $ http is a modified promise why they have success and error, but I suggest using vanilla promise and using .then ()

var deferred = $q.defer();

if (extn === 'xlsx' || extn === 'xls') {
    $http.post(this.uploadUrl, files, {
        transformRequest: angular.identity,
         headers: {
             'Content-Type': undefined
         }
    }).success(function(success) {
        deferred.resolve(success);
    }).error(function(error) {
        deferred.reject(error);
    });
} else {
    deferred.reject('File format not supported');
}
return deferred.promise;

      

and your controller:

$scope.upload = function (filename) {
    fileUploadExcel.doUpload().then(function (success) {
        //success
    }, function (error) {
        //error
    });
}

      

+2


source


The error is thrown when it doUpload()

returns false

. Since it false

is boolean and not promised, it .success()

will not be specified.



Instead of returning false

, I suggest you return a rejected promise when the file is not an Excel file line by line: return $q.reject("File type not supported: " + extn);

+3


source


Have you tried doing this instead?

$scope.upload = function (filename) {
  var promise = fileUploadExcel.doUpload(); //gets promise object in a variable
  if(promise){ // if variable is not false or null, handle resolution
     promise.success(function (success) { }).error(function (error) {});
  }
}

      

Or you can return null

to else

the factory and perform a null check. The above code will remain the same.

+1


source







All Articles