Angular2 uploads files using ng2-file-upload

Keywords: angular Attribute npm

Angular2 uploads files using ng2-file-upload

ng2-file-upload is a fully functional support library for uploading files
(Reference: http://www.jianshu.com/p/0741186f60ab
https://segmentfault.com/a/1190000007886391
http://valor-software.com/ng2-file-upload/)
Angular2 uses ng2-file-upload to upload files:

1. Install ng2-file-upload module:

npm install ng2-file-upload --save

2. Introduce a module into the required module in the app.module.ts file

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

CommonModule and FileUploadModule are then referenced in the imports field of @NgModule.

@NgModule({
    imports: [
        CommonModule,
        FileUploadModule
    ]
}

3. The corresponding app.component.html content (the code is a bit messy, and I don't know why multiple-choice buttons sometimes pop up very slowly)

<div style="text-align:center">
  <h1>
    Welcome to {{title}}!!
  </h1>
</div>
<div>
  <form >
  <h1>Multiple Selection</h1>
  <input type="file" ng2FileSelect [uploader]="uploader" name="fileInput"  id="fileInput" multiple  />
  <!--ng-submit="submit_form()"-->
  <!--<input type="file" name ="filer" ng2FileSelect [uploader]="uploader" (change)="selectedFileOnChanged($event)" multiple   />-->
  <h1>Radio</h1>
  <input type="file" name ="filer" ng2FileSelect [uploader]="uploader" (change)="selectedFileOnChanged($event)" />
  <table class="table bg-white-only b-a">
  <tbody>
      <div *ngFor="let img of values">
      <td><img [src]="img.filePath" style="max-width: 100px; max-height: 100px" ></td>
      <td>{{img.name}} </td>   <td>{{img.size}} MB</td>
      <td ng-show="true">
      </div>
    </tbody>
  </table>
  <tbody>
    <p>Queue length: {{ uploader?.queue?.length }}</p>
    <tr *ngFor="let item of uploader.queue">
      <td><strong>{{ item?.file?.name }}</strong></td>
      <td class="text-center">
        <span *ngIf="item.isSuccess"><i class="glyphicon glyphicon-ok"></i></span>
        <span *ngIf="item.isCancel"><i class="glyphicon glyphicon-ban-circle"></i></span>
        <span *ngIf="item.isError"><i class="glyphicon glyphicon-remove"></i></span>
      </td>
      <td>Success or failure: {{ item.isSuccess  }}</td>
      <td>Failure or not: {{ item.isError   }}</td>
      <td nowrap>
        <button type="button" class="btn btn-success btn-xs"
                (click)="item.upload()" [disabled]="item.isReady || item.isUploading || item.isSuccess">
          <span class="glyphicon glyphicon-upload"></span> Upload
        </button>
        <button type="button" class="btn btn-warning btn-xs"
                (click)="item.cancel()" [disabled]="!item.isUploading">
          <span class="glyphicon glyphicon-ban-circle"></span> Cancel
        </button>
        <button type="button" class="btn btn-danger btn-xs"
                (click)="item.remove(); ">
          <span class="glyphicon glyphicon-trash"></span> Remove
        </button>
      </td>
    </tr>
     <div>
      <div>
        Queue progress:
        <div class="progress" style="">
          <div class="progress-bar" role="progressbar" [ngStyle]="{ 'width': uploader.progress + '%' }"></div>
        </div>
      </div>
      <button type="button" class="btn btn-success btn-s"
              (click)="uploader.uploadAll()" [disabled]="!uploader.getNotUploadedItems().length">
        <span class="glyphicon glyphicon-upload"></span> Upload all
      </button>
      <button type="button" class="btn btn-warning btn-s"
              (click)="uploader.cancelAll()" [disabled]="!uploader.isUploading">
        <span class="glyphicon glyphicon-ban-circle"></span> Cancel all
      </button>
      <button type="button" class="btn btn-danger btn-s"
              (click)="uploader.clearQueue()" [disabled]="!uploader.queue.length">
        <span class="glyphicon glyphicon-trash"></span> Remove all
      </button>
    </div>
    </tbody>
</form>
</div>

4. app.component.ts code:

import { Component,OnInit } from '@angular/core';
import { CommonModule }     from '@angular/common';
import { FileUploadModule } from 'ng2-file-upload';
// A: Introduce FileUpload module
import { FileUploader } from 'ng2-file-upload';
import {ImageUploadModule} from 'angular2-image-upload';
import {ImageFile} from './ImageFile';

import { NgModule, CUSTOM_ELEMENTS_SCHEMA } from '@angular/core';
import { FormsModule } from '@angular/forms';


@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']

})
export class AppComponent {
  values:ImageFile[] = [];
  file: Array<Object>;
  constructor() {
    this.file = [];
  }
  title = 'LPL';
  // B: Initialization defines the uploader variable used to configure the uploader attribute in input
  public uploader:FileUploader = new FileUploader({
  //Address needs to be modified, cross-domain access problems may exist, and need to be resolved through proxy
    url: "/mall-product/test/productFile",
    method: "POST"
  });
 selectedFileOnChanged(event:any) {
    let files = event.target.files;
   for(let i = 0;i < files.length;i++){
   let  imgFile = files[i];
     let file = new ImageFile();
     console.log(imgFile.type.match('image.*')+"");
     // if(imgFile.type.match('image.*')){
     //   continue;
     // }
     file.name = imgFile.name;
     file.size = imgFile.size;
     let fileReader = new FileReader();
     fileReader.readAsDataURL(imgFile);
     fileReader.onload = ( (theFile) =>{
       return (e)=>{
         // console.log(e.target.result);
         let imgPath = e.target.result;
        file.filePath = imgPath;
       };
     })(imgFile);
     this.values.push(file);
   }
  }
}

Reference resources: http://www.jianshu.com/p/0741186f60ab

FileUploader and FileItem

  1. FileUploader Details

FileUploader is the main component of ng2-file-upload, which contains all the processing of files.

3.1 Attribute Details

IsUpload:[boolean] Whether the file is being uploaded.
queue:[array] has dragged or selected all files.
progress:[number] Overall progress of all uploaded files.
options:[FileUploaderOptions] Configuration information for the upload file, as described earlier.
3.2 Method Details

setOptions(options: FileUploaderOptions): void;
Set the configuration information for the upload file.
addToQueue(files: File[], options?: FileUploaderOptions, filters?: FilterFunction[] | string): void;
Manually add files to FileUploader's upload queue.
removeFromQueue(value: FileItem): void;
Removes the specified file from the FileUploader's upload queue.
clearQueue(): void;
Clear all files in the FileUploader upload queue.
uploadItem(value: FileItem): void;
Upload the specified file.
cancelItem(value: FileItem): void;
Cancels the upload of the specified file.
uploadAll(): void;
Upload all files in FileUploader's upload queue.
cancelAll(): void;
Cancel uploading all files in FileUploader's 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;
Gets all the non-uploaded files in the FileUploader upload queue.
getReadyItems(): Array;
Gets all the files in the FileUploader upload queue ready for upload.
destroy(): void;
Destroy the FileUploader instance.
3.3 Monitoring Details

onAfterAddingAll(fileItems: any): any;
Callbacks after adding all files
Return:
fileItems - Array of added files
onBuildItemForm(fileItem: FileItem, form: any): any;
Callback after file creation
Return:
fileItem - File created
form - How to add
onAfterAddingFile(fileItem: FileItem): any;
Callback after adding a file
Return:
fileItem - File added
onWhenAddingFileFailed(item: FileLikeObject, filter: any, options: any): any;
Callbacks that failed to add files
Return:
item -
filter -
options -
onBeforeUploadItem(fileItem: FileItem): any;
Callbacks before uploading files
Return:
fileItem - File to be uploaded
onProgressItem(fileItem: FileItem, progress: any): any;
Progress of file upload (very frequent calls after starting upload)
Return:
fileItem - File being uploaded
Progress - Upload progress of the file
onProgressAll(progress: any): any;
Callbacks to overall upload progress (very frequent calls after starting upload)
Return:
Progress - Overall upload progress
onSuccessItem(item: FileItem, response: string, status: number, headers: ParsedResponseHeaders): any;
Callback to upload a file successfully
Return:
item - File uploaded successfully
response - Server return after successful upload
Status - status code
Headers - Return headers returned by the server after successful upload
onErrorItem(item: FileItem, response: string, status: number, headers: ParsedResponseHeaders): any;
Callback for uploading a file incorrectly
Return:
item - Upload the wrong file
response - Error returned
Status - status code
headers - returned error return header
onCancelItem(item: FileItem, response: string, status: number, headers: ParsedResponseHeaders): any;
Cancel callback for uploading a file
Return:
item - Cancel uploaded file
response - Canceled return information
Status - status code
headers - Return header for canceled return information
onCompleteItem(item: FileItem, response: string, status: number, headers: ParsedResponseHeaders): any;
Callback to finish uploading a file
Return:
item - File uploaded successfully
response - Server return after successful upload
Status - status code
Headers - Return headers returned by the server after successful upload
onCompleteAll(): any;
Complete callback for uploading all files
4. FileItem Details

FileItem is the element type of the queue attribute in FileUploader and the basic type of file stored in FileUploader.

4.1 Attribute Details

alias [string]: Uploaded flag/alias.
url [string]: address.
method [string]: The method to upload.
headers [any]: Uploaded header parameter.
withCredentials: [boolean]: Whether to use a certificate or not.
formData [any]: Format data?
isReady [boolean]: Is it ready to upload (is it possible to upload).
IsUpload [boolean]: Is uploading in progress.
isUploaded [boolean]: Has it been uploaded?
isSuccess [boolean]: Whether the upload was successful or not.
isCancel [boolean]: Cancel upload.
isError [boolean]: Whether to upload errors.
progress [number]: Upload progress.
index [number]: Position in the queue.
4.2 Method Details

upload(): void;
Start uploading this file.
cancel(): void;
Cancel uploading this file.
remove(): void;
Remove this file from the upload queue.
4.3 Monitoring Details

onBeforeUpload(): void;
Callback function before starting upload.
onBuildForm(form: any): any;
Callback function to create file.
Return:
form - File source.
onProgress(progress: number): any;
Progress callback function for uploading files.
Return:
progress - progress of uploading files.
onSuccess(response: string, status: number, headers: ParsedResponseHeaders): any;
Callback function that uploaded the file successfully.
Return:
response - Callback data after success
Status - status code
headers - Return header of callback data
onError(response: string, status: number, headers: ParsedResponseHeaders): any;
Callback function for uploading file errors.
onCancel(response: string, status: number, headers: ParsedResponseHeaders): any;
Cancel the uploaded callback function.
onComplete(response: string, status: number, headers: ParsedResponseHeaders): any;
Callback function for uploading a file.

Posted by synted on Sat, 15 Jun 2019 10:12:55 -0700