AngularJS上传文件示例代码,如何实现多文件上传与进度显示?

AngularJS 作为一款经典的前端框架,在文件上传功能实现上提供了灵活的解决方案,通过结合 ng 模块指令和原生 JavaScript 的 FileReader API,开发者可以轻松构建交互式文件上传模块,以下将从基础实现、进阶优化、错误处理等多个维度,详细解析 AngularJS 文件上传的示例代码与核心逻辑。

AngularJS上传文件示例代码,如何实现多文件上传与进度显示?

基础文件上传实现

AngularJS 文件上传的核心在于利用 ng-model 指令双向绑定文件数据,并通过 ng-submitng-click 触发上传逻辑,以下是一个基础单文件上传的完整示例:

<div ng-app="fileUploadApp" ng-controller="UploadController">
  <form name="uploadForm" ng-submit="submitFile()">
    <input type="file" name="file" ng-model="file" required>
    <button type="submit" ng-disabled="uploadForm.$invalid">上传</button>
  </form>
  <div ng-show="uploadStatus">
    {{uploadStatus}}
  </div>
</div>

对应的控制器代码如下:

angular.module('fileUploadApp', [])
  .controller('UploadController', ['$scope', '$http', function($scope, $http) {
    $scope.submitFile = function() {
      var formData = new FormData();
      formData.append('file', $scope.file);
      $http.post('/api/upload', formData, {
        transformRequest: angular.identity,
        headers: {'Content-Type': undefined}
      })
      .success(function(response) {
        $scope.uploadStatus = '上传成功:' + response.filename;
      })
      .error(function(error) {
        $scope.uploadStatus = '上传失败:' + error.message;
      });
    };
  }]);

关键点解析

  1. FormData 对象:用于构建表单数据流,支持文件与普通字段的混合提交。
  2. transformRequest:设置为 angular.identity 避免 AngularJS 默认的数据序列化,确保文件原始数据正确传输。
  3. Content-Type 设置:通过 headersContent-Type 设为 undefined,让浏览器自动设置正确的 multipart/form-data 边界。

多文件上传与进度显示

实际应用中常需支持多文件上传并显示上传进度,可通过 multiple 属性和 ng-files 指令扩展功能:

<input type="file" name="files" multiple ng-model="files" ng-files="getFiles($files)">

控制器中处理多文件逻辑:

AngularJS上传文件示例代码,如何实现多文件上传与进度显示?

$scope.getFiles = function(fileList) {
  $scope.files = fileList;
};
$scope.uploadMultiple = function() {
  var formData = new FormData();
  for (var i = 0; i < $scope.files.length; i++) {
    formData.append('files', $scope.files[i]);
  }
  $http.post('/api/uploadMultiple', formData, {
    uploadEventHandlers: {
      progress: function(event) {
        $scope.progress = Math.round(event.loaded / event.total * 100);
      }
    },
    transformRequest: angular.identity,
    headers: {'Content-Type': undefined}
  })
  .success(function(response) {
    $scope.uploadStatus = '成功上传 ' + response.length + ' 个文件';
  });
};

进度条实现
可通过 HTML5 的 progress 元素直观展示上传进度:

<progress value="{{progress}}" max="100"></progress>
<span>{{progress}}%</span>

文件类型与大小验证

前端验证能有效减少无效请求,通过 ng-pattern 和自定义指令实现校验:

<input type="file" 
       accept=".jpg,.jpeg,.png,.pdf" 
       ng-model="file" 
       ng-pattern="/.(jpg|jpeg|png|pdf)$/" 
       required>
<div ng-show="uploadForm.file.$error.pattern">仅支持图片和PDF文件</div>

在控制器中添加大小验证:

$scope.$watch('file', function(newFile) {
  if (newFile && newFile.size > 5 * 1024 * 1024) { // 5MB限制
    $scope.fileSizeError = '文件大小不能超过5MB';
    $scope.file = null;
  } else {
    $scope.fileSizeError = '';
  }
});

服务端配置注意事项

虽然本文聚焦前端实现,但服务端配置同样关键,以 Node.js Express 为例:

const multer = require('multer');
const upload = multer({ dest: 'uploads/' });
app.post('/api/upload', upload.single('file'), (req, res) => {
  res.json({ filename: req.file.filename });
});
app.post('/api/uploadMultiple', upload.array('files', 5), (req, res) => {
  res.json(req.files.map(f => f.filename));
});

常见问题与解决方案

问题现象可能原因解决方案
上传失败,提示 413 Request Entity Too Large文件超过服务器限制调整服务端 maxBodySize 配置
进度条不更新浏览器不支持 progress 事件使用 iframe 回退方案
文件类型验证失效accept 属性仅作提示结合 ng-pattern 严格校验

完整优化示例

结合上述所有要素,以下是完整的优化版实现:

AngularJS上传文件示例代码,如何实现多文件上传与进度显示?

<div ng-app="uploadApp" ng-controller="UploadCtrl">
  <form name="uploadForm" ng-submit="uploadFiles()">
    <div class="form-group">
      <label>选择文件(支持多选,最大5MB,类型:jpg/png/pdf)</label>
      <input type="file" 
             name="files" 
             multiple 
             accept=".jpg,.jpeg,.png,.pdf"
             ng-model="selectedFiles"
             ng-required="!selectedFiles.length"
             ng-change="validateFiles()">
      <div class="help-block">
        <span ng-show="uploadForm.files.$error.required">请选择文件</span>
        <span ng-show="fileErrors">{{fileErrors}}</span>
      </div>
    </div>
    <div class="progress" ng-show="progress > 0">
      <div class="progress-bar" role="progressbar" 
           style="width:{{progress}}%">{{progress}}%</div>
    </div>
    <button type="submit" 
            class="btn btn-primary" 
            ng-disabled="uploadForm.$invalid || isUploading">
      {{isUploading ? '上传中...' : '开始上传'}}
    </button>
  </form>
  <div class="alert alert-success" ng-show="uploadSuccess">
    {{uploadSuccess}}
  </div>
</div>

控制器代码:

angular.module('uploadApp', [])
  .controller('UploadCtrl', ['$scope', '$http', function($scope, $http) {
    $scope.isUploading = false;
    $scope.progress = 0;
    $scope.fileErrors = '';
    $scope.validateFiles = function() {
      $scope.fileErrors = '';
      if (!$scope.selectedFiles) return;
      for (var i = 0; i < $scope.selectedFiles.length; i++) {
        var file = $scope.selectedFiles[i];
        if (file.size > 5 * 1024 * 1024) {
          $scope.fileErrors = '文件 ' + file.name + ' 超过5MB限制';
          $scope.selectedFiles = null;
          return;
        }
      }
    };
    $scope.uploadFiles = function() {
      $scope.isUploading = true;
      $scope.progress = 0;
      $scope.uploadSuccess = '';
      var formData = new FormData();
      for (var i = 0; i < $scope.selectedFiles.length; i++) {
        formData.append('files', $scope.selectedFiles[i]);
      }
      $http.post('/api/upload', formData, {
        uploadEventHandlers: {
          progress: function(e) {
            $scope.progress = Math.round(e.loaded / e.total * 100);
            $scope.$apply();
          }
        },
        transformRequest: angular.identity,
        headers: {'Content-Type': undefined}
      })
      .success(function(response) {
        $scope.uploadSuccess = '成功上传 ' + response.length + ' 个文件';
      })
      .error(function(error) {
        $scope.fileErrors = '上传失败:' + error.message;
      })
      .finally(function() {
        $scope.isUploading = false;
      });
    };
  }]);

通过以上代码实现了一个功能完善、交互友好的 AngularJS 文件上传模块,涵盖了基础上传、多文件处理、进度显示、前端验证等核心功能,并提供了清晰的错误反馈机制,开发者可根据实际需求进一步扩展功能,如添加文件预览、断点续传等高级特性。

图片来源于AI模型,如侵权请联系管理员。作者:酷小编,如若转载,请注明出处:https://www.kufanyun.com/ask/55276.html

(0)
上一篇2025年11月4日 12:04
下一篇 2025年11月4日 12:08

相关推荐

  • aop7108监控视频画面不能移动怎么办?

    aop7108监控视频画面不能移动的常见原因与解决方法在安防监控系统中,aop7108作为一款常用的监控设备,其视频画面的稳定性直接关系到监控效果,部分用户可能会遇到“监控视频画面不能移动”的问题,导致摄像头无法正常调整角度或变焦,影响监控范围,本文将从硬件故障、软件设置、网络环境及人为操作四个方面,分析该问题……

    2025年10月29日
    060
  • 昆明服务器租用最新报价是多少?租一个月大概要花多少钱?

    随着数字经济的蓬勃发展,昆明作为我国西南地区的重要中心城市,其互联网基础设施建设和数据中心产业正迎来前所未有的发展机遇,对于众多企业及开发者而言,“昆明服务器租报价”成为了一个备受关注的搜索热点,服务器租用价格并非一个固定的数字,它受到多重因素的综合影响,本文将深入剖析影响昆明服务器租用价格的核心要素,提供主流……

    2025年10月15日
    060
  • 陕西服务器如何实现高速稳定?揭秘关键技术与应用案例

    在信息技术飞速发展的今天,服务器作为支撑网络正常运行的核心设备,其性能和稳定性至关重要,陕西作为我国西部地区的重要经济和文化中心,其服务器市场也呈现出蓬勃发展的态势,本文将从陕西服务器的市场概况、技术特点、应用领域等方面进行详细介绍,陕西服务器市场概况市场规模近年来,随着互联网、大数据、云计算等技术的快速发展……

    2025年11月1日
    030
  • 租用昆明BGP服务器前需要了解哪些关键问题?

    随着数字经济的浪潮席卷全球,企业对网络基础设施的稳定性、访问速度和覆盖范围提出了前所未有的高要求,在这一背景下,昆明,作为中国面向南亚、东南亚的辐射中心和西南地区的重要枢纽,其BGP(边界网关协议)服务器正逐渐成为众多企业布局区域市场的战略要地,它不仅承载着数据,更连接着商机与发展,昆明的独特区位优势选择服务器……

    2025年10月14日
    060

发表回复

您的邮箱地址不会被公开。必填项已用 * 标注