Upload image to Blob through .NET API
Angular+ngx-dropzone send base64 image string to .NET API, encode, send image to Blob, get Url
https://www.base64encoder.io/image-to-base64-converter/ -- copy "Base64 Image source" to upload using API
// upload.module.ts
```
NgxDropzoneModule, /// ngx-dropzone
ReactiveFormsModule,
MatProgressBarModule
```// upload.ts
import { throwDialogContentAlreadyAttachedError } from '@angular/cdk/dialog';
import { Component, OnInit } from '@angular/core';
import { UntypedFormControl, UntypedFormGroup, Validators } from '@angular/forms';
import { ToastrService } from 'ngx-toastr';
import { UploadService } from 'src/app/services/upload.service';
@Component({
selector: 'app-upload-to-blob',
templateUrl: './upload-to-blob.component.html',
styleUrls: ['./upload-to-blob.component.scss']
})
export class UploadToBlobComponent implements OnInit {
shortLink: string = "";
loading: boolean = false; // Flag variable
file: any; // Variable to store file
imageValid: boolean = false;
files: File[] = [];
base64Image: any;
constructor(
private fileUploadService: UploadService,
private toastr: ToastrService,
) { }
ngOnInit(): void {
}
onSubmit() {
this.loading = !this.loading;
var jsonData = {
"FileName": this.files[0].name,
"Image": this.base64Image
}
this.fileUploadService.uploadImageToBlob(jsonData)
.subscribe({
next: (data) => {
if (data.status == 200) {
this.toastr.success('Upload image complate', 'Success');
this.shortLink = data.body.link;
this.loading = false; // Flag variable
}
},
error: (error) => {
// console.log(error);
this.toastr.warning(error.status + ' - upload image Fail', 'Fail');
},
});
}
onSelect(event: any) {
console.log(event);
this.files.length = 0;
this.files.push(...event.addedFiles);
let arrayLength = this.files.length;
// keep one file
this.files.splice(1, arrayLength - 1);
if (arrayLength === 1) {
this.imageValid = true;
this.readFile(this.files[0]).then(fileContents => {
// Put this string in a request body to upload it to an API.
// console.log(fileContents);
this.base64Image = fileContents;
})
}
}
onRemove(event: any) {
console.log(event);
this.files.splice(this.files.indexOf(event), 1);
this.imageValid = false;
}
private async readFile(file: File): Promise<string | ArrayBuffer> {
return new Promise<string | ArrayBuffer>((resolve, reject) => {
const reader = new FileReader();
reader.onload = (e) => {
return resolve((e.target as FileReader).result || '');
};
reader.onerror = e => {
console.error(`FileReader failed on file ${file.name}.`);
return reject(null);
};
if (!file) {
console.error('No file to read.');
return reject(null);
}
reader.readAsDataURL(file);
});
}
}
Last updated
Was this helpful?