Pertama, Anda perlu mengatur HttpClient di proyek Angular Anda.
Buka file src / app / app.module.ts, impor HttpClientModule dan tambahkan ke array impor modul sebagai berikut:
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 { }
Selanjutnya, hasilkan komponen:
$ ng generate component home
Selanjutnya, hasilkan layanan unggahan:
$ ng generate service upload
Selanjutnya, buka file src / app / upload.service.ts sebagai berikut:
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'
});
}
}
Selanjutnya, buka file src / app / home / home.component.ts, dan mulai dengan menambahkan impor berikut:
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';
Selanjutnya, tentukan fileUpload dan variabel file dan masukkan UploadService sebagai berikut:
@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) { }
Selanjutnya, tentukan metode 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);
}
});
}
Selanjutnya, tentukan metode uploadFiles () yang dapat digunakan untuk mengunggah banyak file gambar:
private uploadFiles() {
this.fileUpload.nativeElement.value = '';
this.files.forEach(file => {
this.uploadFile(file);
});
}
Selanjutnya, tentukan metode 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();
}
Selanjutnya, kita perlu membuat template HTML UI unggah gambar kita. Buka file src / app / home / home.component.html dan tambahkan konten berikut:
<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>
Lihatlah tutorial ini dan postingan ini
Choose File
upload btn sederhana ? Bdw dalam kedua kasus Anda cukup mengunggah menggunakan FormData