在Github上找到了一个支持Angular4好用的文件上传组件ng2-file-upload,这里简单介绍一下这个库的集成使用方案。 

本文基于该组件的1.2.1版。

1. 安装

安装非常简单,只要在项目根路径下运行如下npm命令即可:

npm install ng2-file-upload --save

2. 使用说明

官方的文档写的非常简单,几乎看不出什么来,这里结合实际的使用调试,说明一下基本的配置和使用方案。

2.1. 集成到Module中

在需要使用的Module中需要引入如下两个模块:


import { CommonModule } from '@angular/common';
import { FileUploadModule } from 'ng2-file-upload';

@NgModule({

imports: [

CommonModule,
FileUploadModule

],

})
export class ProjectDetailPageModule {}

2.2. 初始化FileUploader

在对应的使用的Component中,需要引入FileUploader

import { FileUploader } from 'ng2-file-upload';

然后声明一个FileUploader类型的变量,并将其初始化:

uploader:FileUploader = new FileUploader({
url: commonConfig.baseUrl + "/uploadFile",
method: "POST",
itemAlias: "uploadedfile",
autoUpload: false
});

初始化FileUploader需要传入FileUploaderOptions类型的参数:

参数名 参数类型 是否是可选值 参数说明
allowedMimeType Array 可选值  
allowedFileType Array 可选值 允许上传的文件类型
autoUpload boolean 可选值 是否自动上传
isHTML5 boolean 可选值 是否是HTML5
filters Array 可选值  
headers Array 可选值 上传文件的请求头参数
method string 可选值 上传文件的方式
authToken string 可选值 auth验证的token
maxFileSize number 可选值 最大可上传文件的大小
queueLimit number 可选值  
removeAfterUpload boolean 可选值 是否在上传完成后从队列中移除
url string 可选值 上传地址
disableMultipart boolean 可选值  
itemAlias string 可选值 文件标记/别名
authTokenHeader string 可选值 auth验证token的请求头

2.2.1. 关键参数说明

  • headers: 这里参数一个Array类型,数组内接收的类型为{name: 'headerName', value: 'haederValue'},例如:
this.uploader = new FileUploader({
url: commonConfig.baseUrl + "/uploadFile",
method: "POST",
itemAlias: "uploadedfile",
autoUpload: false,
headers:[
{name:"x-AuthenticationToken",value:"dd32fdfd32fs23fds9few"}
]
});
  • autoUpload: 是否自动上传,如果为true,则通过<input type="file"/>选择完文件后立即自动上传,为false则需要手工调用uploader.uploadAll()或者uploader.uploadItem(value: FileItem)方法进行手工上传。
  • allowedFileType: 这个文件类型并非我们认为的文件后缀,不管选择哪一个值,并不会过滤弹出文件选择时显示的文件类型,只是选择后,非该类型的文件会被过滤掉,例如allowedFileType:["image","xls"],可选值为:

    • application
    • image
    • video
    • audio
    • pdf
    • compress
    • doc
    • xls
    • ppt
  • allowedMimeType: 这个是通过Mime类型进行过滤,例如allowedMimeType: ['image/jpeg', 'image/png' ],跟上面的allowedFileType参数一样,不管选择哪一个值,并不会过滤弹出文件选择时显示的文件类型,只是选择后,非该类型的文件会被过滤掉。

2.3. FileUploader常用事件绑定

注意基于uploader事件绑定的函数其默认scope为uploader自身,所以如果想在对应的绑定函数中使用其他scope对象,需要使用bind函数处理对应的绑定函数,如下:

this.uploader.onSuccessItem = this.successItem.bind(this);

下面介绍三个常用的事件

2.3.1. onAfterAddingFile

onAfterAddingFile(fileItem: FileItem): any;

  • 触发时机:添加一个文件之后的回调
  • 参数:
    • fileItem - 添加的文件信息,FileItem类型。

2.3.2. onSuccessItem

onSuccessItem(item: FileItem, response: string, status: number, headers: ParsedResponseHeaders): any;

  • 触发时机:上传一个文件成功后回调
  • 参数:
    • item - 上传成功的文件信息,FileItem类型;
    • response - 上传成功后服务器的返回信息;
    • status - 状态码;
    • headers - 上传成功后服务器的返回的返回头。

2.3.3. onBuildItemForm

onBuildItemForm(fileItem: FileItem, form: any): any;

  • 触发时机:创建文件之后的回调,大约是在进行实际的上传前,这个事件经常用来对form进行处理,用以传递一些文件以外的业务相关信息。
    例如:
this.uploader.onBuildItemForm = this.buildItemForm;

buildItemForm(fileItem: FileItem, form: any): any{
if(!!fileItem["realFileName"]){
form.append("fileName",fileItem["realFileName"]);
}
}
  • 参数:

    •   fileItem - 要上传的文件信息,FileItem类型;
    •   form - 表单信息,用来添加文件相关的业务信息,方便后台处理,FormData类型。

2.4. Template中文件上传控件处理

2.4.1 input file控件处理

在组件对应的HTML模版中设置input标签:

<input type="file" ng2FileSelect [uploader]="uploader" (change)="selectedFileOnChanged($event)" />

在组件.ts文件中设置声明函数:

selectedFileOnChanged() {
// 这里是文件选择完成后的操作处理
}

选择文件默认支持选择单个文件,如需支持文件多选,请在标签中添加multiple属性,即:

<input type="file" ng2FileSelect [uploader]="uploader" (change)="selectedFileOnChanged($event)" multiple />

2.4.2 支持文件多选的实现示例

下面是参考官方示例改造的一个文件多选时的template及相关后台代码的配置示例:

<ion-card>
<ion-card-header>
文件上传操作
</ion-card-header>
<ion-card-content>
<input #fileUpload hidden=true type="file" ng2FileSelect [uploader]="uploader" (change)="selectedFileOnChanged($event)" multiple />
<button (click)="fileSelect()" >选择文件</button>
<button (click)="fileAllUp()" >全部上传</button>
<button (click)="fileAllCancel()" >全部取消</button>
<button (click)="fileAllDelete()" >清除列表</button>
</ion-card-content>
</ion-card>
<ion-card>
<ion-card-header>
上传文件列表
</ion-card-header>
<ion-card-content>
<p>已选文件数量: {{ uploader?.queue?.length }}</p>
<ion-grid>
<ion-row>
<ion-col col-2="">名称</ion-col>
<ion-col col-2="">保存名</ion-col>
<ion-col col-2="">文件大小</ion-col>
<ion-col col-2="">进度</ion-col>
<ion-col col-1="">状态</ion-col>
<ion-col col-3="">操作</ion-col>
</ion-row> <ion-row *ngFor="let item of uploader.queue">
<ion-col col-2><strong>{{ item?.file?.name }}</strong></ion-col>
<ion-col col-2><input type="text" (change)="changeFileName($event, item)"></ion-col>
<ion-col col-2>
<span>{{ item?.file?.size/1024/1024 | number:'.2' }} MB</span>
</ion-col> <ion-col col-2>
<div class="progress" style="margin-bottom: 0; height: 70%; width: 90%">
<div class="progress-bar" style="margin-bottom: 0; height: 100%; background-color: red" role="progressbar" [ngStyle]="{ 'width': item.progress + '%' }"></div>
</div>
</ion-col>
<ion-col col-1>
<span *ngIf="item.isSuccess">成功</span>
<span *ngIf="!item.isUploaded">未上传</span>
<span *ngIf="item.isCancel">取消</span>
<span *ngIf="item.isError">错误</span>
</ion-col>
<ion-col col-3>
<button (click)="item.upload()" [disabled]="item.isReady || item.isUploading || item.isSuccess">
上传
</button>
<button (click)="item.cancel()" [disabled]="!item.isUploading">
取消
</button>
<button (click)="item.remove()">
清除
</button>
</ion-col>
</ion-row>
</ion-grid>
</ion-card-content>
</ion-card>
@ViewChild('firstInput', { read: MdInputDirective })
firstInput: MdInputDirective;
@ViewChild('fileUpload')
fileUpload: ElementRef;

this.uploader = new FileUploader({
url: commonConfig.baseUrl + "/uploadFile",
method: "POST",
itemAlias: "uploadedfile",
autoUpload: false
});
this.uploader.onSuccessItem = this.successItem.bind(this);
this.uploader.onAfterAddingFile = this.afterAddFile;
this.uploader.onBuildItemForm = this.buildItemForm;

fileSelect(): any{
this.fileUpload.nativeElement.click();
}
fileAllUp(): any{
this.uploader.uploadAll();
}
fileAllCancel(): any{
this.uploader.cancelAll();
}
fileAllDelete(): any{
this.uploader.clearQueue();
} selectedFileOnChanged(event) {
// 这里是文件选择完成后的操作处理
} buildItemForm(fileItem: FileItem, form: any): any{
if(!!fileItem["realFileName"]){
form.append("fileName",fileItem["realFileName"]);
}
} afterAddFile(fileItem: FileItem): any{ }
changeFileName(value: any, fileItem: FileItem){
fileItem["realFileName"] = value.target.value;
}
successItem(item: FileItem, response: string, status: number, headers: ParsedResponseHeaders):any{
// 上传文件成功
if (status == 200) {
// 上传文件后获取服务器返回的数据
let tempRes = JSON.parse(response);
}else {
// 上传文件后获取服务器返回的数据错误
}
console.info(response+" for "+item.file.name + " status " + status);
}

2.4.3 文件拖拽上传实现

拖拽文件默认支持多文件拖拽。
对块级元素进行设置(这里以div标签为例):

<div class="beforeDrop" ng2FileDrop [ngClass]="{dropping: isDropZoneOver}" (fileOver)="fileOverBase($event)" (onFileDrop)="fileDropOver($event)" [uploader]="uploader"><div>

在组件.ts文件中设置声明函数:

fileOverBase(event) {
// 拖拽状态改变的回调函数
}
fileDropOver(event) {
// 文件拖拽完成的回调函数
}

参考:
Angular2使用ng2-file-upload上传文件

Angular4集成ng2-file-upload的更多相关文章

  1. 定制jQuery File Upload为微博式单文件上传

    日志未经声明,均为AlloVince原创.版权采用『 知识共享署名-非商业性使用 2.5 许可协议』进行许可. jQuery File Upload是一个非常优秀的上传组件,主要使用了XHR作为上传方 ...

  2. jQuery File Upload 单页面多实例的实现

    jQuery File Upload 的 GitHub 地址:https://github.com/blueimp/jQuery-File-Upload 插件描述:jQuery File Upload ...

  3. jQuery File Upload done函数没有返回

    最近在使用jQuery File Upload 上传图片时发现一个问题,发现done函数没有callback,经过一番折腾,找到问题原因,是由于dataType: ‘json’造成的,改为autoUp ...

  4. kindeditor多图片上传找不到action原来是private File upload成员变量惹得祸

    kindeditor多图片上传找不到action原来是private File upload成员变量惹得祸

  5. 【转发】Html5 File Upload with Progress

    Html5 File Upload with Progress               Posted by Shiv Kumar on 25th September, 2010Senior Sof ...

  6. 用jQuery File Upload做的上传控件demo,支持同页面多个上传按钮

    需求 有这么一个需求,一个form有多个文件要上传,但又不是传统的图片批量上传那种,是类似下图这种需求,一开始是用的swfupload做的上传,但是问题是如果有多个按钮的话,就要写很多重复的代码,于为 ...

  7. jquery file upload 文件上传插件

    1. jquery file upload 下载 jquery file upload Demo 地址:https://blueimp.github.io/jQuery-File-Upload/ jq ...

  8. jQuery File Upload跨域上传

    最近在做一个一手粮互联网项目,方案为前后端分离,自己负责前端框架,采用了Requirejs+avalonjs+jquery三个框架完成. 前后端通过跨域实现接口调用,中间也发现了不少问题,尤其是在富文 ...

  9. 《Play for Java》学习笔记(六)文件上传file upload

    一. Play中标准方法 使用表单form和multipart/form-data的content-type类型. 1.Form @form(action = routes.Application.u ...

  10. [转]Maintain File Upload Control on Postbacks

    本文转自:http://www.ironspeed.com/articles/Maintain%20File%20Upload%20Control/Article.aspx Introduction ...

随机推荐

  1. Python multiprocessing.Manager介绍和实例(进程间共享数据)

    Python中进程间共享数据,处理基本的queue,pipe和value+array外,还提供了更高层次的封装.使用multiprocessing.Manager可以简单地使用这些高级接口. Mana ...

  2. 算法入门经典-第七章 例题7-4-1 拓展 n皇后问题 回溯法

    实际上回溯法有暴力破解的意思在里面,解决一个问题,一路走到底,路无法通,返回寻找另   一条路. 回溯法可以解决很多的问题,如:N皇后问题和迷宫问题. 一.概念 回溯算法实际类似枚举的搜索尝试过程,主 ...

  3. Android开发:ImageView阴影和图层效果

    import android.app.Activity; import android.content.Context; import android.graphics.Bitmap; import  ...

  4. Jq自定义的方法绑定树结构

    1.先上效果图  (借鉴博客) 2.这边不做样式的只做结构 function toTreeData(data) { var pos = {}; var tree = []; var i = 0; wh ...

  5. TESTUSERB 仅能对TESTUSERA 用户下的某些表增删改查、有些表仅能对某些列update,查询TESTUSERB 用户权限,获取批量赋予语句。

    TESTUSERB 仅能对TESTUSERA 用户下的某些表增删改查.有些表仅能对某些列update,查询TESTUSERB 用户权限,获取批量赋予语句. select 'grant '|| PRIV ...

  6. ZBrush中平滑笔刷介绍

    平滑笔刷在ZBrush®中的使用颇多,它可以在ZBrush®模型的多层细分下工作,并且能够控制对模型的平滑效果,而且还能将模型的细节完整保留.默认情况下,按住Shift键就会切换到平滑笔刷,根据调整不 ...

  7. servlet实现定时刷新功能

    1,继承httpservlet类重写doget个dopost方法 2,发送头消息 response.setHeader("refresh","间隔秒数:url=目标地址& ...

  8. pytorch 7 save_reload 保存和提取神经网络

    import torch import matplotlib.pyplot as plt # torch.manual_seed(1) # reproducible # fake data x = t ...

  9. LeetCode 11. Container With Most Water 单调队列

    题意 Given n non-negative integers a1, a2, ..., an, where each represents a point at coordinate (i, ai ...

  10. Virtual Box 新建一个虚拟机安装系统(补充:WIN7 64 bit 系统虚拟机无法安装 64 bit 系统问题)

    1.安装Virtual Box好后,点击新建 2.配置内存大小,这个根据自己需要配置就好 3.创建虚拟硬盘 这里选择固定分配.动态分配都可以,接下来就分配硬盘大小了 4.新建好后我们点击刚才建立的虚拟 ...