Converting Files To Base64 In Angular 2+
Stackblitz | Stackblitz
app.component.html
Angular 2+ 2021
<div><button class="btn" (click)="file.click()">Tải ảnh lên</button><input#filetype="file"(click)="$event.target.value = null"(change)="onFileSelected(file.files)"multiple="multiple"accept=".png, .jpg, .jpeg, .gif"class="d-none"/><br><br><ng-container *ngFor="let item of selectedFiles"><a [href]="item.base64"><img [src]="item.base64" width="200px" height="150px" /></a></ng-container><h5 class="author">Author DaiDH</h5></div>
app.component.ts
Angular 2+ 2021
import { Component } from '@angular/core';import { AsyncSubject, Observable } from 'rxjs';export interface SelectedFiles {name: string;file: any;base64?: string;}@Component({selector: 'my-app',templateUrl: './app.component.html',styleUrls: [ './app.component.css' ]})export class AppComponent {public selectedFiles : SelectedFiles[] = [];public toFilesBase64(files: File[], selectedFiles: SelectedFiles[]): Observable<SelectedFiles[]> {const result = new AsyncSubject<SelectedFiles[]>();if (files?.length) {Object.keys(files)?.forEach(async (file, i) => {const reader = new FileReader();reader.readAsDataURL(files[i]);reader.onload = (e) => {selectedFiles = selectedFiles?.filter(f => f?.name != files[i]?.name)selectedFiles.push({ name: files[i]?.name, file: files[i], base64: reader?.result as string })result.next(selectedFiles);if (files?.length === (i + 1)) {result.complete();}};});return result;} else {result.next([]);result.complete();return result;}}public onFileSelected(files: File[]) {// this.selectedFiles = []; // clearthis.toFilesBase64(files, this.selectedFiles).subscribe((res: SelectedFiles[]) => {this.selectedFiles = res;});}}
0 nhận xét:
Post a Comment