Home > Web Front-end > JS Tutorial > body text

Angular4 integrates the upload component of ng2-file-upload

亚连
Release: 2018-05-30 11:16:27
Original
2665 people have browsed it

This article mainly introduces the upload component of Angular4 integrated with ng2-file-upload. Now I share it with you and give it as a reference.

I found a file upload component ng2-file-upload that supports Angular4 on Github. Here is a brief introduction to the integrated use of this library.

This article is based on version 1.2.1 of this component.

1. Installation

Installation is very simple, just run the following npm command in the project root path:

npm install ng2-file-upload --save
Copy after login

2. Instructions for use

The official document is very simple and can hardly be seen. Here we explain the basic configuration and usage plan based on actual usage and debugging.

2.1. Integrate into Module

The following two modules need to be introduced into the Module that needs to be used:

…
import { CommonModule } from '@angular/common';
import { FileUploadModule } from 'ng2-file-upload';
…
@NgModule({
 …
 imports: [
 …
 CommonModule,
 FileUploadModule
 …
 ],
 …
})
export class ProjectDetailPageModule {}
Copy after login

2.2. Initialization FileUploader

In the corresponding Component used, FileUploader needs to be introduced:

import { FileUploader } from 'ng2-file-upload';
Copy after login

Then declare a variable of FileUploader type and initialize it:

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

Initialization FileUploader needs to pass in parameters of FileUploaderOptions type:

##urlstringOptional valueUpload addressdisableMultipartbooleanOptional ValueitemAliasstringOptional valueFile tag/aliasauthTokenHeaderstringOptional valueauth verification token request header

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"}
 ]
});
Copy after login

autoUpload: 是否自动上传,如果为true,则通过选择完文件后立即自动上传,为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);
Copy after login

下面介绍三个常用的事件

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"]);
 }
}
Copy after login

参数:

  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)" />
Copy after login

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

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

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

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

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:&#39;.2&#39; }} MB</span>
  </ion-col>

  <ion-col col-2>
   <p class="progress" style="margin-bottom: 0; height: 70%; width: 90%">
   <p class="progress-bar" style="margin-bottom: 0; height: 100%; background-color: red" role="progressbar" [ngStyle]="{ &#39;width&#39;: item.progress + &#39;%&#39; }"></p>
   </p>
  </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>
Copy after login
@ViewChild(&#39;firstInput&#39;, { read: MdInputDirective })
firstInput: MdInputDirective;
@ViewChild(&#39;fileUpload&#39;)
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);
}
Copy after login

2.4.3 文件拖拽上传实现

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

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

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

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

上面是我整理给大家的,希望今后会对大家有帮助。

相关文章:

js中apply和Math.max()函数的问题及区别介绍

浅谈Vue内置component组件的应用场景

vue2中使用less简易教程

The above is the detailed content of Angular4 integrates the upload component of ng2-file-upload. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
Parameter nameParameter typeWhether it is an optional valueParameter description
allowedMimeTypeArrayOptional value
allowedFileTypeArrayOptional valueFile types allowed to be uploaded
autoUpload booleanOptional valueWhether to automatically upload
isHTML5booleanOptional Whether the value is HTML5
filtersArrayOptional value
headersArrayOptional valueRequest header parameters for uploading files
methodstringOptional valueHow to upload files
authTokenstringOptional valueauth verification token
maxFileSizenumberOptional valueMaximum The size of the uploadable file
queueLimitnumberOptional value
removeAfterUploadbooleanOptional valueWhether to remove from the queue after the upload is completed