Step 1: Below are the sample code of converting an file to base64. Copy and past the code on your HTML page.
<div class="wrapper dashboard-h">
<div class="container-fluid">
<p> </p>
<div class="row">
<div class="col-md-9" style="margin: 0 auto;">
<div class="card m-b-30">
<div class="card-body">
<form name="form" [formGroup]="empForm" (ngSubmit)="UploadFile()">
<div class="row">
<div class="col-md-12">
<label for="type" class="col-form-label">
File Upload :
<span class="error">*</span>
</label>
<div class="form-group">
<div class="file-upload-custom w-100">
<input id="FU_Id" type="file" formControlName="FU_Doc" accept=".jpeg,.JPG,.png,.pdf"
(change)="fnFileName($event,'FileName')"
[ngClass]="{ 'is-invalid': submitted && FU_Doc?.errors }" />
<input type="text" readonly="readonly" class="form-control" formControlName="FileName">
<button type="button" class="btn btn-primary btn-sm">Browse File</button>
</div>
(jpg/jpeg/png/pdf Files only)
<div *ngIf="submitted && FU_Doc?.errors" class="error">
<div *ngIf="FU_Doc?.errors.required">required</div>
</div>
<br />
</div>
</div>
<div class="text-center m-t-20">
<button type="submit" class="btn btn-raised btn-primary btn-lg">Submit</button>
</div>
</div>
</form>
</div>
</div>
</div>
</div>
</div>
Step 2: Code of TS. Copy and past the code on your page.
import { Component, OnInit } from '@angular/core';
import { Validators, FormGroup, FormBuilder } from '@angular/forms';
import { ToastrService } from 'ngx-toastr';
import { AdminService } from '../Service/admin.service';
@Component({
selector: 'app-test',
templateUrl: './test.component.html',
styleUrls: ['./test.component.css']
})
export class TestComponent implements OnInit {
empForm: FormGroup;
submitted: boolean = false;
ApplicantId: any="123456";
constructor(
private _adminService:AdminService, //Create your own Admin Service to send the record on server.
private formBuilder: FormBuilder,
private toasterService: ToastrService) { }
ngOnInit() {
this.empForm = this.formBuilder.group({
FU_Doc: ['', Validators.required],
FileName:['', Validators.required],
FileBase64:[''],
FileType:['']
});
debugger;
}
ConvertFile(file: any,FileBase64: any) {
debugger;
var reader = new FileReader();
reader.readAsDataURL(file);
reader.onload = function () {
let data = reader.result.toString().replace(/^data:(.*,)?/, '');
FileBase64.setValue(data);
FileBase64.updateValueAndValidity();
debugger;
//console.log(data);
};
reader.onerror = function (error) {
console.log('Error: ', error);
return "";
};
}
fnFileName($event,CtrName:string) {
debugger
let file = $event.target.files[0];
let fileSize = $event.target.files[0].size;
const FileBase64 = this.empForm.get("FileBase64");
const documentPath = this.empForm.get(CtrName);
const type = this.empForm.get("FileType");
if (fileSize <= 2097152) {
debugger;
let _name = $event.target.files[0].name;
documentPath.setValue(_name);
documentPath.updateValueAndValidity();
let _type = $event.target.files[0].type;
type.setValue(_type);
type.updateValueAndValidity();
this.ConvertFile(file,FileBase64);
}
else {
documentPath.setValue('');
documentPath.updateValueAndValidity();
type.setValue('');
type.updateValueAndValidity();
this.toasterService.error("File size should be less than or equal to 2MB.");
return false;
}
}
UploadFile() {
debugger
this.submitted = true;
// stop here if form is invalid
if (this.empForm.invalid) {
this.toasterService.error("Requred field can not be blank.");
return;
}
debugger;
let param = {
ApplicantId: this.ApplicantId,
FileData: this.empForm.value.FileBase64,
FileName:this.empForm.value.FileName,
Filetype: this.empForm.value.FileType
}
//Create your own Admin Service to send the record on server.
this._adminService.UploadFile(param)
.subscribe(result => {
if (result.type == "Success") {
this.toasterService.success(result.message);
}
else {
this.toasterService.error(result.message);
}
this.toasterService.success("Record updated successfully.");
})
}
}
import { Injectable } from '@angular/core';
import { HttpClient, HttpHeaders } from '@angular/common/http';
import { Observable } from 'rxjs';
import { environment } from '../../environments/environment'
import { IShowMessage } from '../Interface/IShowMessage';
@Injectable({
providedIn: 'root'
})
export class AdminService {
private BASE_API_URL = environment.BASE_API_URL;
private _controllerName: string = "Admin/";
private _url: string = this.BASE_API_URL + this._controllerName;
private _methodName: string = "";
private _param: {};
//private _paramObj: {};
private httpOptions = {
_headers: new HttpHeaders({
'Content-Type': 'applicantion/json'
})
};
constructor(private _http: HttpClient) {
console.log('Hello Service Provider');
}
UploadFile(_source: any): Observable<IShowMessage> {
this._methodName = "UploadFile/";
this._param = _source;
return this._http.post<IShowMessage>(
this._url + this._methodName, this._param
)
}
}
Step 4: The POST method that is used in ASP.NET Core to save the file on serve.
[HttpPost]
[Route("UploadFile")]
public ShowMessage UploadFile([FromBody]FileDate imageData)
{
ShowMessage ShowMessage = new ShowMessage();
try
{
ApplicantDAL obj = new ApplicantDAL();
if(!string.IsNullOrEmpty(imageData.FileData))
{
//Root Folder path;
string webRootPath =
_hostingEnvironment.WebRootPath;
string filename = DateTime.Now.ToString("yyyyMMddHHmmss") + '_' +
imageData.FileName;
bool folderExists =
System.IO.Directory.Exists(webRootPath + "\\ApplicantForm\\" + imageData.ApplicantId + "\\");
if (!folderExists)
Directory.CreateDirectory(webRootPath
+ "\\ApplicantForm\\" + imageData.ApplicantId + "\\");
imageData.Path =
webRootPath + "\\ApplicantForm\\" + imageData.ApplicantId + "\\" + filename;
imageData.FileName =
filename;
if (!String.IsNullOrEmpty(imageData.FileData))
{
using (FileStream fs = new FileStream(imageData.Path,
FileMode.Create))
{
using (BinaryWriter bw = new BinaryWriter(fs))
{
byte[] data =
Convert.FromBase64String(imageData.FileData);
bw.Write(data);
bw.Close();
}
}
//Here you can write your own function to save the file name on
database.
}
}
//you can
return any value to show success message.
return ShowMessage.Show("Record updated
successfully.", ShowMessage.messageType.Success);
}
catch (Exception ex)
{
//ErrorLogger.Log(ex.Message);
//ErrorLogger.Log(ex.StackTrace);
return ShowMessage.Show("Invalid", ShowMessage.messageType.Error);
}
}
Great post.
ReplyDeletehttps://pbase.com/manueljackson/profile
Great post.
ReplyDeletehttps://www.inprnt.com/profile/charlielauzon/
Great post.
ReplyDeletehttps://medium.com/@souravdhar002/why-online-courses-are-more-effective-than-traditional-bb210b6bb84
Great post.
ReplyDeletehttps://www.debate.org/HowardLarosa/