欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

Angular4集成ng2-file-upload的上传组件

程序员文章站 2022-10-05 18:37:45
在github上找到了一个支持angular4好用的文件上传组件ng2-file-upload,这里简单介绍一下这个库的集成使用方案。 本文基于该组件的1.2.1版。...

在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"],可选值为:

  1. application
  2. image
  3. video
  4. audio
  5. pdf
  6. compress
  7. doc
  8. xls
  9. 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;

触发时机:上传一个文件成功后回调

参数:

  1.  item - 上传成功的文件信息,fileitem类型;
  2. response - 上传成功后服务器的返回信息;
  3. status - 状态码;
  4. 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"]);
 }
}

参数:

  1. fileitem - 要上传的文件信息,fileitem类型;
  2. 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) {
 // 文件拖拽完成的回调函数
}

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。