Angular与Laravel模态框文件上传:无法正确触发大小超限错误提示
问题分析与解决方案
问题根源
你使用的ngf-max-size(ng-file-upload指令)在检测到文件超出大小限制时,会自动将$scope.file置为null。这直接导致:
- 原逻辑先判断
!$scope.file,超大文件会触发“请先选择文档”的提示,而非预期的大小超限提示。 - 若调换判断顺序先检查
$scope.file.size,此时$scope.file已为null,访问size会抛出错误,后续所有判断逻辑都无法执行,导致无任何提示。
修复方案
利用ng-file-upload的表单验证机制获取错误状态,同时调整判断逻辑避免空值报错:
修改后的HTML代码
<div class="col-md-6"> <label for="name">Name:</label> <input type="text" class="form-control-sm" required ng-model="document.name" placeholder="Name of Document" style="width:200%"><br/><br/><br/> <form name="form"> <input type="file" required ng-model="file" name="file" accept="file/*" ngf-select="" ngf-max-size="10MB" > <br/><br/> <a ng-if="file" href="{{file.url}}">{{file.file_name}}</a> <button type="button" class="btn btn-info btn-sm" ng-click="uploadDocument()">Upload</button> </form> </div>
修改后的控制器代码
$scope.uploadDocument = function () { $scope.document.company_id = $scope.employee.comp_fk; // 检查文档名称 if(!$scope.document.name){ swal({ title: "Please enter document name.", type: "warning" }); return; } // 检查文件选择状态及错误类型 if(!$scope.file){ if($scope.form.file.$error.maxSize){ swal({ title: "The file size of the document you are trying to upload exceeds the 10MB limit.", type: "warning" }); } else { swal({ title: "Please select a document first.", type: "warning" }); } return; } // 兜底手动大小校验(防止指令失效) const MAX_SIZE = 10 * 1024 * 1024; // 10MB if($scope.file.size > MAX_SIZE) { swal({ title: "The file size of the document you are trying to upload exceeds the 10MB limit.", type: "warning" }); return; } // 执行上传逻辑 var data = { 'file' : $scope.file, 'document' : $scope.document }; Documents.uploadDocument(data).then(function (response) { var data = response.data; var success = data.success; $scope.loading = false; if (success) { $scope.document=data.document; $scope.success = true; swal({ title: "Document Saved!", text: "Document successfully saved.", type: "success" }) }else{ swal({ title: "Server Error!", text: "Saving not successful. Kindly retry", type: "error" }, function(){ $scope.closeModal(); $route.reload(); }) } $scope.files = {}; }); };
关键改动说明
- 借助表单
$scope.form.file.$error.maxSize状态,直接获取ngf-max-size触发的大小超限错误,避免因file被清空导致的判断偏差。 - 每个错误判断后添加
return,确保触发提示后不再执行后续逻辑。 - 增加手动大小校验作为兜底,防止指令异常时的漏判。
内容的提问来源于stack exchange,提问作者Nash
相关产品推荐
相关产品推荐

