简体   繁体   English

Angularjs如何获取文件扩展名?

[英]Angularjs how to get filename extension?

Hi I am developing angularjs application. 嗨,我正在开发angularjs应用程序。 I am doing file upload module. 我正在做文件上传模块。 I am trying to validate the files. 我正在尝试验证文件。 I want to upload only xlsx or xls files. 我只想上传xlsx或xls文件。 I have developed directive and factory method to upload files as 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 am able to get extn successfully. 我能够成功地获得成功。 When my files are of type excel my code works fine. 当我的文件是excel类型时,我的代码工作正常。 Whenever i upload other than excel i am getting error. 每当我上传excel以外我都会收到错误。 I have wrote return false. 我写过返回false。 This is not working here. 这不适用于此。 I should return something else may be. 我应该返回别的东西。 May i know what i should write in else case? 我可以知道在其他情况下我应该写些什么吗? Can anyone help me out here? 有人可以帮我从这里出去吗? Any help would be appreciated. 任何帮助,将不胜感激。 Thank you. 谢谢。

The error is thrown when doUpload() returns false . doUpload()返回false时抛出false Since false is a boolean and not a promise, there is .success() won't be defined. 因为false是布尔值而不是promise,所以不会定义.success()

Instead of returning false I suggest you return a rejected promise when the file is not an excel file along the lines of: return $q.reject("File type not supported: " + extn); 而不是返回false我建议您在文件不是excel文件时返回被拒绝的承诺: return $q.reject("File type not supported: " + extn);

You return different type: 你返回不同的类型:

on success, you return a $http promise in your factory, so you can call success & error function in your controller whith that: 成功时,您在工厂中返回$ http承诺,因此您可以在控制器中调用成功和错误功能:

fileUploadExcel.doUpload().success() exist! fileUploadExcel.doUpload().success() 存在!

but if error, you return false in your factory, in this case this is a boolean and is not a $http promise so you cant use success & error function. 但如果出现错误,则在工厂中返回false,在这种情况下,这是一个布尔值,并且不是$ http承诺,因此您无法使用成功和错误函数。

fileUploadExcel.doUpload().success() doesnt exist and return an error fileUploadExcel.doUpload().success() 不存在并返回错误

Of course a solution is to check if the returning value is not false and continue your code, but I suggest to return always a promise by resolving it if success and rejecting it on error, so the promise chain is a not broken. 当然,一个解决方案是检查返回值是否为false并继续您的代码,但我建议通过解析它,如果成功并在出错时拒绝它,则始终返回一个承诺, 因此承诺链不会被破坏。

PS: $http is a modified promise why they have success & error, but I suggest using the vanilla promise and using .then() PS:$ http是一个修改过的承诺,为什么他们有成功和错误,但我建议使用vanilla承诺并使用.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
    });
}

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 in else in your factory and do a null check. 或者您可以在工厂中的else中返回null并执行空检查。 The code above will remain same. 上面的代码将保持不变。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM