Home Web Front-end JS Tutorial Angular4 integrates the upload component of ng2-file-upload

Angular4 integrates the upload component of ng2-file-upload

May 30, 2018 am 11:16 AM
components

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!

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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to install the Windows 10 old version component DirectPlay How to install the Windows 10 old version component DirectPlay Dec 28, 2023 pm 03:43 PM

Many users always encounter some problems when playing some games on win10, such as screen freezes and blurred screens. At this time, we can solve the problem by turning on the directplay function, and the operation method of the function is also Very simple. How to install directplay, the old component of win10 1. Enter "Control Panel" in the search box and open it 2. Select large icons as the viewing method 3. Find "Programs and Features" 4. Click on the left to enable or turn off win functions 5. Select the old version here Just check the box

How to implement calendar component using Vue? How to implement calendar component using Vue? Jun 25, 2023 pm 01:28 PM

Vue is a very popular front-end framework. It provides many tools and functions, such as componentization, data binding, event handling, etc., which can help developers build efficient, flexible and easy-to-maintain Web applications. In this article, I will introduce how to implement a calendar component using Vue. 1. Requirements analysis First, we need to analyze the requirements of this calendar component. A basic calendar should have the following functions: display the calendar page of the current month; support switching to the previous month or next month; support clicking on a certain day,

VUE3 development basics: using extends to inherit components VUE3 development basics: using extends to inherit components Jun 16, 2023 am 08:58 AM

Vue is one of the most popular front-end frameworks currently, and VUE3 is the latest version of the Vue framework. Compared with VUE2, VUE3 has higher performance and a better development experience, and has become the first choice of many developers. In VUE3, using extends to inherit components is a very practical development method. This article will introduce how to use extends to inherit components. What is extends? In Vue, extends is a very practical attribute, which can be used for child components to inherit from their parents.

Angular components and their display properties: understanding non-block default values Angular components and their display properties: understanding non-block default values Mar 15, 2024 pm 04:51 PM

The default display behavior for components in the Angular framework is not for block-level elements. This design choice promotes encapsulation of component styles and encourages developers to consciously define how each component is displayed. By explicitly setting the CSS property display, the display of Angular components can be fully controlled to achieve the desired layout and responsiveness.

Let's talk about how Vue dynamically renders components through JSX Let's talk about how Vue dynamically renders components through JSX Dec 05, 2022 pm 06:52 PM

How does Vue dynamically render components through JSX? The following article will introduce to you how Vue can efficiently dynamically render components through JSX. I hope it will be helpful to you!

How to open the settings of the old version of win10 components How to open the settings of the old version of win10 components Dec 22, 2023 am 08:45 AM

Win10 old version components need to be turned on by users themselves in the settings, because many components are usually closed by default. First we need to enter the settings. The operation is very simple. Just follow the steps below. Where are the win10 old version components? Open 1. Click Start, then click "Win System" 2. Click to enter the Control Panel 3. Then click the program below 4. Click "Enable or turn off Win functions" 5. Here you can choose what you want to open

Vue component development: implementation method of progress bar component Vue component development: implementation method of progress bar component Nov 24, 2023 am 08:56 AM

Vue component development: Progress bar component implementation method Preface: In Web development, the progress bar is a common UI component, often used to display the progress of operations in scenarios such as data requests, file uploads, and form submissions. In Vue.js, we can easily implement a progress bar component by customizing components. This article will introduce an implementation method and provide specific code examples. I hope it will be helpful to Vue.js beginners. Component structure and style First, we need to define the basic structure and style of the progress bar component.

Vue component practice: paging component development Vue component practice: paging component development Nov 24, 2023 am 08:56 AM

Vue component practice: Introduction to paging component development In web applications, the paging function is an essential component. A good paging component should be simple and clear in presentation, rich in functions, and easy to integrate and use. In this article, we will introduce how to use the Vue.js framework to develop a highly customizable paging component. We will explain in detail how to develop using Vue components through code examples. Technology stack Vue.js2.xJavaScript (ES6) HTML5 and CSS3 development environment

See all articles
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