简体   繁体   中英

how to implement file-upload using angular 6?

im trying to create a component in witch i implemented file upload function in a child component and then i'm trying to use that component's selector in an other one : my project structure is like that :

- upload : 
upload.component.html 
upload.component.ts
upload.module.ts

in this package i implemented this code : upload.component.html :

    <div class="row">
<div class="col-12">


  <ngfFormData [files]="files" postName="file" [(FormData)]="sendableFormData"></ngfFormData>

  <ngfUploadStatus [(percent)]="progress" [httpEvent]="httpEvent"></ngfUploadStatus>


  <div class="inline-block">



  </div>

  <div>
    <h3>Drop Files</h3>
    <div class="border padding-15 border-radius bg-white mb-2">
      <div class="inline-block">
        <div ngfDrop [(validDrag)]="baseDropValid" (fileOver)="hasBaseDropZoneOver=$event" [(files)]="files" [accept]="accept" [maxSize]="maxSize"
          [(dragFiles)]="dragFiles" [(lastInvalids)]="lastInvalids" class="well my-drop-zone" [class.invalid-drag]="baseDropValid===false"
          [class.valid-drag]="baseDropValid" (filesChange)="lastFileAt=getDate()">
          <p class="font">Glisser/Déposer le document ou choisir un document...</p>
        </div>

      </div>
    </div>




  </div>
  <div class="inline-block">
    <strong>maxSize in bytes</strong>
    <div>
      <input type="number" [(ngModel)]="maxSize" placeholder="1024 == 1mb" />
    </div>
  </div>

  <div *ngIf="dragFiles">
    <h3 style="margin:0">Drag Files</h3>
    <p *ngIf="!dragFiles.length" style="color:red;">
      This browser does NOT release metadata for files being dragged. All files will be considered valid drags until dropped.
    </p>
    <pre>{{ dragFiles | json }}</pre>
  </div>

  <div class="bg-warning" *ngIf="lastInvalids?.length" style="margin-bottom: 40px">
    <h3 style="color:red;">Last {{ lastInvalids.length }} Invalid Selected Files</h3>

    <table class="table">
      <thead>
        <tr>
          <th>Name</th>
          <th>Error</th>
          <th>Type</th>
          <th>Size</th>
          <th>Actions</th>
        </tr>
      </thead>
      <tbody>
        <tr *ngFor="let item of lastInvalids;let i=index">
          <td>
            <div *ngIf="['image/gif','image/png','image/jpeg'].indexOf(item.file.type)>=0">
              <div class="previewIcon" [ngfBackground]="item.File"></div>
            </div>
            <strong>{{ item.file.name }}</strong>
          </td>
          <td nowrap>
            {{ item.type }}
          </td>
          <td nowrap>
            {{ item.file.type }}
          </td>
          <td nowrap>
            {{ item.file.size/1024/1024 | number:'.2' }} MB
          </td>
          <td nowrap>
            <button type="button" class="btn btn-danger btn-xs" (click)="lastInvalids.splice(i,1)">
              <span class="glyphicon glyphicon-trash"></span>
            </button>
          </td>
        </tr>
      </tbody>
    </table>
  </div>

  <div style="margin-bottom: 40px">
    <h3>{{ files.length }} Queued Files</h3>
    <table class="table">
      <thead>
        <tr>
          <th>Name</th>
          <th>Type</th>
          <th>Size</th>
          <th>Actions</th>
        </tr>
      </thead>
      <tbody>
        <tr *ngFor="let item of files;let i=index">
          <td>
            <div *ngIf="['image/gif','image/png','image/jpeg'].indexOf(item.type)>=0">
              <div class="previewIcon" [ngfBackground]="item"></div>
            </div>
            <strong>{{ item.name }}</strong>
          </td>
          <td nowrap>
            {{ item.type }}
          </td>
          <td nowrap>
            {{ item.size/1024/1024 | number:'.2' }} MB
          </td>
          <td nowrap>

            <i class="icons icon-file_delete pointer" (click)="files.splice(i,1)"></i>

          </td>
        </tr>
      </tbody>
    </table>

    <div>
      <div>
        Queue progress:
        <div class="progress" style="">
          <div class="progress-bar" role="progressbar" [ngStyle]="{ 'width': progress + '%' }"></div>
        </div>
      </div>

      <ng-container *ngIf="lastFileAt">
        <p>
          <strong>Last file(s) selected At:</strong> {{ lastFileAt | date : 'longTime' }}
        </p>
      </ng-container>

      <i *ngIf="progress==100" class="glyphicon glyphicon-ok"></i>

      <button (click)="uploadFiles(files)" >
        Upload all
      </button>

      <button (click)="cancel()" >
        Cancel all
      </button>
      <button (click)="files.length=0" >
        Remove all
      </button>
    </div>
  </div>
</div>

upload.component.ts :

  import { Component, OnInit, NgModule  } from '@angular/core';
  import { ngfModule, ngf } from "angular-file";
  import {
  HttpClient, HttpRequest, HttpResponse, HttpEvent
 } from "@angular/common/http";
 import { platformBrowserDynamic } from "@angular/platform-browser-dynamic";
 import { BrowserModule } from '@angular/platform-browser';
 import { Subscription } from 'rxjs';

  @Component({
  selector: 'sof-upload',
   templateUrl: './upload.component.html',
  styleUrls: ['./upload.component.scss']
   })
 export class UploadComponent implements OnInit {
 accept = '*'
 files:File[] = []
 progress:number
 url = 'https://evening-anchorage-3159.herokuapp.com/api/'
 hasBaseDropZoneOver:boolean = false
 httpEmitter:Subscription
 httpEvent:HttpEvent<{}>
 lastFileAt:Date

  sendableFormData:FormData//populated via ngfFormData directive
   constructor(public HttpClient:HttpClient) { }

   cancel(){
  this.progress = 0
  if( this.httpEmitter ){
  console.log('cancelled')
  this.httpEmitter.unsubscribe()
  }
  }

  uploadFiles(files:File[]):Subscription{
  const req = new HttpRequest<FormData>('POST', this.url, 
 this.sendableFormData, {
    reportProgress: true//, responseType: 'text'
  })

  return this.httpEmitter = this.HttpClient.request(req)
.subscribe(
  event=>{
    this.httpEvent = event

    if (event instanceof HttpResponse) {
      delete this.httpEmitter
      console.log('request done', event)
      }
     },
   error=>console.log('Error Uploading',error)
    )
   }

   getDate(){
   return new Date()
   }
   ngOnInit() {

  }



   }

upload.module.ts:

 import { NgModule } from '@angular/core';
 import { CommonModule } from '@angular/common';
 import { UploadComponent } from './upload.component';

 @NgModule({
 imports: [
    CommonModule,

    ],
   declarations: [UploadComponent],
   providers: [],
   exports: [UploadComponent]
     })
  export class UploadModule { }

then i tried to call its selector in an other component so i just created the component and added :

<sof-upload></sof-upload>

i added the first component module in my app.module.ts but im getting this error that i couldn't solve :

Uncaught Error: Template parse errors:
Can't bind to 'files' since it isn't a known property of 'ngfFormData'. ("


  <ngfFormData [ERROR ->][files]="files" postName="file" [(FormData)]="sendableFormData"></ngfFormData>

  <ngfUploadS"): ng:///UploadModule/UploadComponent.html@4:19
Can't bind to 'FormData' since it isn't a known property of 'ngfFormData'. ("


  <ngfFormData [files]="files" postName="file" [ERROR ->][(FormData)]="sendableFormData"></ngfFormData>

  <ngfUploadStatus [(percent)]="progress" [ht"): ng:///UploadModule/UploadComponent.html@4:51
'ngfFormData' is not a known element:
1. If 'ngfFormData' is an Angular component, then verify that it is part of this module.
2. To allow any element add 'NO_ERRORS_SCHEMA' to the '@NgModule.schemas' of this component. ("


  [ERROR ->]<ngfFormData [files]="files" postName="file" [(FormData)]="sendableFormData"></ngfFormData>

"): ng:///UploadModule/UploadComponent.html@4:6
Can't bind to 'percent' since it isn't a known property of 'ngfUploadStatus'. ("="files" postName="file" [(FormData)]="sendableFormData"></ngfFormData>

  <ngfUploadStatus [ERROR ->][(percent)]="progress" [httpEvent]="httpEvent"></ngfUploadStatus>

just solved that by adding ngfModule to the imports of the child module. Great example to use so enjoy trying it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM