Innanzitutto, devi configurare HttpClient nel tuo progetto angolare.
Aprire il file src / app / app.module.ts, importare HttpClientModule e aggiungerlo all'array import del modulo come segue:
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
import { HttpClientModule } from '@angular/common/http';
@NgModule({
declarations: [
AppComponent,
],
imports: [
BrowserModule,
AppRoutingModule,
HttpClientModule
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }
Quindi, genera un componente:
$ ng generate component home
Successivamente, genera un servizio di caricamento:
$ ng generate service upload
Quindi, apri il file src / app / upload.service.ts come segue:
import { HttpClient, HttpEvent, HttpErrorResponse, HttpEventType } from '@angular/common/http';
import { map } from 'rxjs/operators';
@Injectable({
providedIn: 'root'
})
export class UploadService {
SERVER_URL: string = "https://file.io/";
constructor(private httpClient: HttpClient) { }
public upload(formData) {
return this.httpClient.post<any>(this.SERVER_URL, formData, {
reportProgress: true,
observe: 'events'
});
}
}
Quindi, apri il file src / app / home / home.component.ts e inizia aggiungendo le seguenti importazioni:
import { Component, OnInit, ViewChild, ElementRef } from '@angular/core';
import { HttpEventType, HttpErrorResponse } from '@angular/common/http';
import { of } from 'rxjs';
import { catchError, map } from 'rxjs/operators';
import { UploadService } from '../upload.service';
Successivamente, definire le variabili fileUpload e file e iniettare UploadService come segue:
@Component({
selector: 'app-home',
templateUrl: './home.component.html',
styleUrls: ['./home.component.css']
})
export class HomeComponent implements OnInit {
@ViewChild("fileUpload", {static: false}) fileUpload: ElementRef;files = [];
constructor(private uploadService: UploadService) { }
Quindi, definire il metodo uploadFile ():
uploadFile(file) {
const formData = new FormData();
formData.append('file', file.data);
file.inProgress = true;
this.uploadService.upload(formData).pipe(
map(event => {
switch (event.type) {
case HttpEventType.UploadProgress:
file.progress = Math.round(event.loaded * 100 / event.total);
break;
case HttpEventType.Response:
return event;
}
}),
catchError((error: HttpErrorResponse) => {
file.inProgress = false;
return of(`${file.data.name} upload failed.`);
})).subscribe((event: any) => {
if (typeof (event) === 'object') {
console.log(event.body);
}
});
}
Successivamente, definisci il metodo uploadFiles () che può essere utilizzato per caricare più file di immagine:
private uploadFiles() {
this.fileUpload.nativeElement.value = '';
this.files.forEach(file => {
this.uploadFile(file);
});
}
Quindi, definire il metodo onClick ():
onClick() {
const fileUpload = this.fileUpload.nativeElement;fileUpload.onchange = () => {
for (let index = 0; index < fileUpload.files.length; index++)
{
const file = fileUpload.files[index];
this.files.push({ data: file, inProgress: false, progress: 0});
}
this.uploadFiles();
};
fileUpload.click();
}
Successivamente, dobbiamo creare il modello HTML della nostra interfaccia utente per il caricamento delle immagini. Apri il file src / app / home / home.component.html e aggiungi il seguente contenuto:
<div style="text-align:center; margin-top: 100px; ">
<button mat-button color="warn" (click)="onClick()">
Upload
</button>
<input type="file" #fileUpload id="fileUpload" name="fileUpload" multiple="multiple" accept="image/*" style="display:none;" /></div>
Dai un'occhiata a questo tutorial e a questo post
Choose File
caricare btn? Bdw in entrambi i casi è sufficiente caricare utilizzando FormData