首页
/ ng-file-upload 文件上传组件使用指南

ng-file-upload 文件上传组件使用指南

2025-07-07 02:54:32作者:董灵辛Dennis

概述

ng-file-upload 是一个强大的 AngularJS 文件上传组件,提供了丰富的功能和灵活的配置选项。本文将详细介绍如何使用该组件实现各种文件上传场景。

基本配置

引入依赖

首先需要在 HTML 中引入必要的 JavaScript 文件:

<script src="js/ng-file-upload-shim.js"></script>
<script src="js/ng-file-upload.js"></script>
<script src="js/upload.js"></script>

初始化设置

可以通过 FileAPI 对象进行全局配置:

FileAPI = {
  debug: true,  // 开启调试模式
  // 其他可选配置
  // jsPath: '/js/FileAPI.min.js/folder/',
  // staticPath: '/flash/FileAPI.flash.swf/folder/'
};

基础文件上传

表单提交上传

<form name="myForm">
  <fieldset>
    <legend>表单提交上传</legend>
    Username: <input type="text" name="userName" ng-model="username" required>
    Profile Picture: 
    <input type="file" ngf-select ng-model="picFile" name="file" 
           ngf-accept="'image/*'" required>
    <button ng-disabled="!myForm.$valid" ng-click="uploadPic(picFile)">提交</button>
    <img ngf-src="picFile" class="thumb">
    <span class="progress" ng-show="picFile.progress >= 0">
      <div style="width:{{picFile.progress}}%" ng-bind="picFile.progress + '%'"></div>
    </span>
  </fieldset>
</form>

关键指令说明

  • ngf-select: 启用文件选择功能
  • ngf-accept: 限制可选择的文件类型
  • ngf-src: 预览选中的文件
  • ng-model: 绑定选中的文件对象

高级功能

拖拽上传

<div ngf-drop ng-model="files" class="drop-box">
  Select File <span ng-show="dropAvailable"> or Drop File</span>
</div>

文件验证

<input type="file" ngf-select ng-model="files" 
       ngf-validate="{size: {min: 10, max: 20}, width: {min: 100, max: 1000}}">

图片处理

<input type="file" ngf-select ng-model="files"
       ngf-resize="{width: 100, height: 100, quality: 0.9, type: 'image/jpeg'}">

上传方式选择

ng-file-upload 支持多种上传方式:

  1. multipart/form-data 上传 (跨浏览器兼容)

    Upload.upload({
      url: '/upload',
      data: {file: file}
    });
    
  2. 二进制内容上传 (仅支持HTML5浏览器)

    Upload.http({
      url: '/upload',
      data: file
    });
    
  3. 云存储服务 直接上传

    Upload.upload({
      url: 'https://storage.example.com/' + bucketName,
      fields: {
        key: file.name,
        serviceKey: serviceKey,
        acl: 'private',
        policy: policy,
        signature: signature,
        'Content-Type': file.type
      },
      file: file
    });
    

进度显示与中断

<span class="progress" ng-show="f.progress >= 0">
  <div style="width:{{f.progress}}%">{{f.progress}}%</div>
</span>
<button ng-click="f.upload.abort()" ng-show="f.upload">取消上传</button>

响应处理

<div ng-show="f.result">
  <a ng-click="f.showDetail = !f.showDetail">详情</a>
  <div ng-show="f.showDetail">
    <div>{{f.result}}</div>
  </div>
</div>

移动端优化

<input type="file" ngf-select ng-model="files" ngf-capture="camera">

最佳实践

  1. 对于图片上传,建议使用 ngf-resize 在客户端进行压缩
  2. 大文件上传时,考虑使用分块上传功能
  3. 对于移动端,可以结合 ngf-capture 直接调用摄像头
  4. 使用 ngf-validate 在客户端进行初步验证,减少无效上传

常见问题

  1. 文件大小限制:可以通过 ngf-validate 设置
  2. 文件类型限制:使用 ngf-acceptngf-pattern
  3. 跨浏览器兼容性:组件已处理大部分兼容性问题
  4. 上传进度显示:通过 progress 属性获取

通过本文介绍,您应该已经掌握了 ng-file-upload 的核心功能和使用方法。该组件提供了丰富的配置选项,可以满足各种复杂的文件上传需求。