如何检查文件的扩展名并验证从谷歌驱动器上传的文件

时间:2017-10-31 05:38:48

标签: javascript angularjs

我有一个选择标签有3个选项,powerpoint,pdf和电子表格,我从谷歌驱动器上传它未经验证,这意味着如果我给ppt链接到pdf选项它正在上传。请帮我验证一下。

我的代码是

<div class="row widget-row" ng-if="mediaData.mediaType == 14">
     <div class="form-group">
         <label>Document Type*</label> 
         <select class="form-control" ng-model="mediaData.googleDocType" required>
              <option value="0" >Powerpoint</option>
              <option value="2" id="spreadsheet">Spreadsheet</option>
              <option value="3">PDF</option>
         </select>
     </div>
</div>

<div class="row widget-row" ng-if="mediaData.mediaType == 14">
     <div class="form-group">
           <label>Link *</label> 
           <input type="text" class="form-control" ng-model="mediaData.docLink" required>
     </div>
</div>

AngularJs代码是

case '14' : $scope.googleDocumentObject = new GoogleDocumentObject();
                if(mediaData.googleDocType == 0){
                    $scope.googleDocumentObject.source = mediaData.docLink;
                    $scope.googleDocumentObject.attributes.documentType = 0;
                    $scope.updateProgram("googlePPT",$scope.googleDocumentObject,1,$scope.cssObject);
                }
                else if(mediaData.googleDocType == 1){

                    $scope.googleDocumentObject.source = mediaData.docLink;
                    $scope.googleDocumentObject.attributes.documentType = 1;
                    $scope.updateProgram("googleDocument",$scope.googleDocumentObject,1,$scope.cssObject);
                }
                else{
                    $scope.googleDocumentObject.source = mediaData.docLink;
                    console.log($scope.googleDocumentObject.source);
                    $scope.googleDocumentObject.attributes.documentType = 2;
                    $scope.updateProgram("googleDocument",$scope.googleDocumentObject,1,$scope.cssObject);
                }
                break;

1 个答案:

答案 0 :(得分:0)

mediaData.link.split('.').pop();的链接或自定义函数中的regex获取文件扩展名。    此函数返回一个布尔标志,以使用mediaData.googleDocType枚举检查其有效性。

case '14':
  $scope.googleDocumentObject = new GoogleDocumentObject();
  var isValid = CheckIfValidFile(mediaData);
  if (isValid) {
    //Upload accordingly
  }
  break;

function CheckIfValidFile(mediaData) {
    var ext = mediaData.link.split('.').pop();
    //Or using below regex
    var re = /(?:\.([^.]+))?$/;
    var ext = re.exec(mediaData.link)[1];

    if ((ext === 'ppt' || ext === 'pptx') && mediaData.googleDocType == 0) {
      return true;
    } else((ext === 'doc' || ext === 'docx') && mediaData.googleDocType == 1) {
      return true;
    } else(ext === 'pdf' && mediaData.googleDocType == 2) {
      return true;
    }
    return false;
}