File: /var/dev/nowruzgan/admin/src/app/services/file.service.ts
import { Injectable } from '@angular/core';
import { GenericService } from './generic.service';
import { Media } from '../data.types';
import { environment } from '../../environments/environment';
import { Observable, Subscriber, catchError, map, of } from 'rxjs';
import { HttpHeaders } from '@angular/common/http';
@Injectable()
export class FileService extends GenericService {
upload(file: File): Observable<string> {
const formData = new FormData();
formData.append('file', file);
return this.http
.post(`${environment.apiBase}/file`, formData, {headers: new HttpHeaders({'x-token': GenericService.userData.token || ''})})
.pipe(
map((result: any) => result.fid),
catchError(error => {
this.handleError(error);
return of('false');
}));
}
readFrom(blob: Blob): Observable<string> {
return Observable.create((observer: Subscriber<string>): void => {
let reader = new FileReader();
reader.onloadend = event => {
let arrayBuffer: any = reader.result;
let binary = String.fromCharCode.apply(null, Array.prototype.slice.apply(new Uint8Array(arrayBuffer)));
observer.next(binary);
observer.complete();
};
reader.readAsArrayBuffer(blob);
});
}
async remove(media: Media): Promise<boolean> {
try {
await this.http
.delete(`${environment.apiBase}/file/${media.uuid}`, this.headers)
.toPromise();
return true;
}catch(error: any) {
this.handleError(error);
return false;
}
}
}