在Angular文件管理器中上传时如何检测文件名

时间:2018-01-20 07:19:23

标签: javascript angularjs angular-file-upload

我正在使用Angular File Manager在我当前的Angularjs App中。

我希望在上传目录中存在名称的文件时向用户显示错误(例如:存在文件名)。

$scope.uploadFiles = function () {

    /*******  I added these ↓↓↓ ********/
    var item = $scope.singleSelection();
    if (item) {
       var name = item.tempModel.name.trim();
       var nameExists = $scope.fileNavigator.fileNameExists(name);
       if (nameExists && validateSamePath(item)) {
          // this name is exist, so ↓
          $scope.apiMiddleware.apiHandler.error = $translate.instant('error_invalid_filename');
          return false;
       }
    }

/******* these code are exist before(your code) ↓↓↓ ********/

$scope.apiMiddleware.upload($scope.uploadFileList, $scope.fileNavigator.currentPath).then(function () {
       $scope.fileNavigator.refresh();
       $scope.uploadFileList = [];
       $scope.modal('uploadfile', true);
    }, function (data) {
       var errorMsg = data.result && data.result.error || $translate.instant('error_uploading_files');
       $scope.apiMiddleware.apiHandler.error = errorMsg;
    });
}

但在这种情况下,我应该选择一个项目然后上传文件,意味着,如果我没有选择文件并上传一个同名的新文件,则不会出现错误。 我需要检测上传的文件fileName

我如何实现这一目标? 提前致谢

1 个答案:

答案 0 :(得分:0)

我在许多搜索和测试代码之后解决了这个问题。

如果重复,我会在文件名中添加时间戳。

在main.js文件中

function checkRepetitive(file) {
    var currentList = $scope.fileNavigator.fileList;
    var repetitive = false;
    angular.forEach(currentList, function (item, index) {
       if (item.model.name === file.name) {
          repetitive = true
       }
    });

    return repetitive;
}


// click on upload file button in upload modal
$scope.uploadFiles = function () {

    angular.forEach($scope.uploadFileList, function (item, index) {

       if (checkRepetitive(item)) {

          // `morteza.jpg` => `morteza` + `new Date().getTime()).toString()` + `.jpg`
          var lastDotIndex = item.name.lastIndexOf('.');
          var fileName = item.name.substring(0, lastDotIndex);
          var extension = item.name.substring(lastDotIndex, item.name.length);

          // name was `read only` so, I can't change that if didn't write this ↓
          Object.defineProperty(item, 'name', {
             writable: true
          });

          angular.extend(item, {'name': fileName + (new Date().getTime()).toString() + extension});

       } // if (checkRepetitive(item)) {

 });