angular image upload component to api code example
Example 1: angualar image upload service
postFile(fileToUpload: File): Observable<boolean> {
const endpoint = 'your-destination-url';
const formData: FormData = new FormData();
formData.append('fileKey', fileToUpload, fileToUpload.name);
return this.httpClient
.post(endpoint, formData, { headers: yourHeadersConfig })
.map(() => { return true; })
.catch((e) => this.handleError(e));
}
Example 2: angular image upload
class ImageSnippet {
constructor(public src: string, public file: File) {}
}
@Component({
selector: 'bwm-image-upload',
templateUrl: 'image-upload.component.html',
styleUrls: ['image-upload.component.scss']
})
export class ImageUploadComponent {
selectedFile: ImageSnippet;
constructor(private imageService: ImageService){}
processFile(imageInput: any) {
const file: File = imageInput.files[0];
const reader = new FileReader();
reader.addEventListener('load', (event: any) => {
this.selectedFile = new ImageSnippet(event.target.result, file);
this.imageService.uploadImage(this.selectedFile.file).subscribe(
(res) => {
},
(err) => {
})
});
reader.readAsDataURL(file);
}
}