Angular2 Uploading files using Ng2-file-upload

Source: Internet
Author: User

ANGULAR2 has two of the more useful upload files of the third-party library, one is ng2-file-upload , one is ng2-uploader . ng2-uploaderis a lightweight upload file support library, the function is weak, but ng2-file-upload is a feature more comprehensive upload file support library. Here ng2-file-upload is the main introduction of the use.

The following are described in the Mac OS operating system.

1. Installation

Install with NPM. To open terminal in the project, run the command:

sudo npm install ng2-file-upload --save

If you are packaging in a way that requires you to systemjs open the file after installation systemjs.config.js , enter the System.config following fields in the last line in the map field:

‘ng2-file-upload‘:            ‘npm:ng2-file-upload‘

System.configEnter the packages last line in the field:

‘ng2-file-upload‘: {        main: ‘index.js‘,        defaultExtension: ‘js‘}

You can then use it in your project.

2. Use

To reference the module in a module that needs to be used:

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

Then @NgModule refer to and in the imports field CommonModule FileUploadModule .

Reference within the component that corresponds to the need to use:

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

Initialize FileUploader :

new FileUploader({        url: "http://www.download.com:80/uploadFile",       method: "POST",        itemAlias: "uploadedfile"});

Initialize FileUploader parameters that require incoming FileUploaderOptions types:

| Name of parameter | Parameter type | is an optional value | Parameter Description |
|:---- --:|:--------:|:-------------:|:--------:|
| Allowedmimetype | array<string> | Optional values | |
| Allowedfiletype | array<string> | Selectable values | Allowed file types to upload |
| Autoupload | Boolean | Selectable values | Whether to upload automatically |
| isHTML5 | Boolean | Selectable values | Whether it is HTML5 |
| Filters | array<filterfunction> | Optional values | |
| Headers | array| Method | string | Selectable values | How to upload Files |
| AuthToken | string | Selectable values | Auth Verified Tokens |
| MaxFileSize | number | Selectable values | Maximum size of an uploaded file |
| Queuelimit | number | Optional values | |
| Removeafterupload | Boolean | Selectable values | Whether to remove from the queue after uploading |
| URL | string | Selectable values | Upload Address |
| Disablemultipart | Boolean | Optional values | |
| Itemalias | string | Selectable values | File Tags/aliases |
| Authtokenheader | string | Selectable values | Auth verifying token's request header |

2.1 Select File

To set the label in the HTML template for the component input :

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

To set the declaration function in the component .ts file:

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

Select File default support to select a single file, if you want to support file multi-Select, please add the attribute in the label multiple , namely:

type="file" ng2FileSelect [uploader]="uploader" (change)="selectedFileOnChanged($event)" multiple />
2.2 Dragging files

Drag-and-drop files support multiple file dragging by default.
Set the Block-level element (here, div for example, the label):

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

To set the declaration function in the component .ts file:

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

FileUploaderThere are a number of types of properties queue , which are all dragged and selected files, as long as the operation of this property can be uploaded file.

this.uploader.queue[0].onSuccess = (response, status, headers) => {        // 上传文件成功 if (status == 200) { // 上传文件后获取服务器返回的数据 let tempRes = JSON.parse(response); }else { // 上传文件后获取服务器返回的数据错误 }};this.uploader.queue[0].upload(); // 开始上传
3. Fileuploader detailed

FileUploaderIs the most important part of Ng2-file-upload, which contains all the processing of files.

3.1 Property Details
    • Isuploading:[Boolean] is uploading the file.
    • Queue:[Array<fileitem>] All files that have been dragged or selected.
    • Progress:[number] the overall progress of all uploaded files.
    • Options:[fileuploaderoptions] upload the configuration information of the file, described earlier.
3.2 Detailed methods
  • setoptions (options:fileuploaderoptions): void;
    Sets the configuration information for the uploaded file.
  • Addtoqueue (files:file[], options?: Fileuploaderoptions, Filters?: filterfunction[] | string): void;
    Manually add files to FileUploader the upload queue.
  • RemoveFromQueue (Value:fileitem): void;
    FileUploaderremoves the specified file from the upload queue.
  • Clearqueue (): void;
    Clears FileUploader all files in the upload queue.
  • Uploaditem (Value:fileitem): void;
    Uploads the specified file.
  • Cancelitem (Value:fileitem): void;
    Cancels the upload of the specified file.
  • Uploadall (): void;
    Upload FileUploader All files in the upload queue.
  • Cancelall (): void;
    Cancels FileUploader the upload of all the files in the upload queue.
  • Isfile (Value:any): boolean;
    Determine if it is a file.
  • Getindexofitem (Value:any): number;
    Gets the location of the file in the FileUploader upload queue.
  • Getnotuploadeditems (): array<any>;
    Gets FileUploader all the files that are not uploaded in the upload queue.
  • Getreadyitems (): array<any>;
    Gets FileUploader all the files in the upload queue that are ready to be uploaded.
  • Destroy (): void;
    Destroys an FileUploader instance.
3.3 Detailed monitoring
  • Onafteraddingall (Fileitems:any): any;
    Callback after all files have been added
    Return:
  • Fileitems-An array of added files
  • Onbuilditemform (Fileitem:fileitem, form:any): any;
    Callback after creating a file
    Return:
  • Fileitem-Created file
  • Form-How to add
  • Onafteraddingfile (Fileitem:fileitem): any;
    Callback after adding a file
    Return:
  • Fileitem-Added Files
  • Onwhenaddingfilefailed (Item:filelikeobject, Filter:any, options:any): any;
    Add a file failed callback
    Return:
  • Item-
  • Filter-
  • Options-
  • Onbeforeuploaditem (Fileitem:fileitem): any;
    Callbacks before uploading a file
    Return:
  • Fileitem-Files that will be uploaded
  • Onprogressitem (Fileitem:fileitem, progress:any): any;
    The progress of uploading the file (very frequently after starting the upload)
    Return:
  • Fileitem-Files that are being uploaded
  • Progress-Upload progress for this file
  • Onprogressall (Progress:any): any;
    A callback for the overall upload progress (very frequent calls after starting the upload)
    Return:
  • Progress-the overall progress of uploading files
  • Onsuccessitem (Item:fileitem, response:string, Status:number, headers:parsedresponseheaders): any;
    Upload a successful callback for a file
    Return:
  • Item-Upload a successful file
  • Response-Return of the server after successful upload
  • Status-State code
  • Headers-Return header of the server after successful upload
  • Onerroritem (Item:fileitem, response:string, Status:number, headers:parsedresponseheaders): any;
    Uploading a file with a wrong callback
    Return:
  • Item-Upload the wrong file
  • Response-Error returned
  • Status-State code
  • Headers-returned error return header
  • Oncancelitem (Item:fileitem, response:string, Status:number, headers:parsedresponseheaders): any;
    Cancel the callback for uploading a file
    Return:
  • Item-Cancel the uploaded file
  • Response-Cancellation of return information
  • Status-State code
  • Headers-Return header for canceled return information
  • Oncompleteitem (Item:fileitem, response:string, Status:number, headers:parsedresponseheaders): any;
    Complete the callback to upload a file
    Return:
  • Item-Upload a successful file
  • Response-Return of the server after successful upload
  • Status-State code
  • Headers-Return header of the server after successful upload
  • Oncompleteall (): any;
    Complete the callback to upload all files
4. Fileitem detailed

FileItemis the basic type of the file that is stored in the FileUploader queue element type of the attribute FileUploader .

4.1 Property Details
    • Alias [string] : Uploaded flag/alias.
    • URL [string] : Address.
    • Method [string] : How to upload.
    • Headers [Any] : Upload the header parameters.
    • Withcredentials: [Boolean] : whether to use certificates.
    • FormData [any] : Format data?
    • IsReady [Boolean] : Ready to upload (whether or not to upload).
    • Isuploading [Boolean] : Whether uploading is in progress.
    • Isuploaded [Boolean] : Whether it has been uploaded.
    • Issuccess [Boolean] : Whether the upload was successful.
    • Iscancel [Boolean] : Whether to cancel the upload.
    • IsError [Boolean] : whether the upload error.
    • Progress [number] : Upload progress.
    • Index [number] : The position in the queue.
4.2 Detailed methods
    • Upload (): void;
      Start uploading this file.
    • Cancel (): void;
      Cancel uploading this file.
    • Remove (): void;
      The file is removed from the upload queue.
4.3 Detailed monitoring
    • Onbeforeupload (): void;
      The callback function before starting the upload.
    • Onbuildform (Form:any): any;
      The callback function that creates the file.
      Return:
    • Form-The source of the file.
    • OnProgress (Progress:number): any;
      The progress callback function for uploading files.
      Return:
    • Progress-progress of uploading files.
    • Onsuccess (response:string, Status:number, headers:parsedresponseheaders): any;
      The callback function that uploaded the file successfully.
      Return:
    • Response-Post-successful callback data
    • Status-State code
    • Headers-Return header for callback data
    • OnError (response:string, Status:number, headers:parsedresponseheaders): any;
      The callback function that uploaded the file error.
    • OnCancel (response:string, Status:number, headers:parsedresponseheaders): any;
      Cancels the upload of the callback function.
    • OnComplete (response:string, Status:number, headers:parsedresponseheaders): any;
      The callback function that uploads the file to complete.


Shmily taking Middle
Links: Https://www.jianshu.com/p/0741186f60ab
Source: Pinterest
The copyright of the book is owned by the author, and any form of reprint should be contacted by the author for authorization and attribution.

Angular2 Uploading files using Ng2-file-upload

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.