Navigation

Wednesday 1 January 2020

Converting an file to base64 in angular 7


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>&nbsp;</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 { ComponentOnInit } from '@angular/core';
import { ValidatorsFormGroupFormBuilder } 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 {

  empFormFormGroup
  submittedboolean = false;
  ApplicantIdany="123456";
  constructor
    private _adminService:AdminService//Create your own Admin Service to send the record on server.
    private formBuilderFormBuilder,
    private toasterServiceToastrService) { }

  ngOnInit() {
    this.empForm = this.formBuilder.group({
      FU_Doc: [''Validators.required],
      FileName:[''Validators.required],
      FileBase64:[''],
      FileType:['']
    });  
    debugger;
  }

  ConvertFile(fileany,FileBase64any) {
    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."); 
        })
    }
  }


Step 3: Service through which UploadFile  function called. Copy and past the code on your AdminService.ts  file.


import { Injectable } from '@angular/core';
import { HttpClientHttpHeaders } 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 _controllerNamestring = "Admin/";
  private _urlstring = this.BASE_API_URL + this._controllerName;
  private _methodNamestring = "";
  private _param: {};
  //private _paramObj: {};
  private httpOptions = {
    _headers: new HttpHeaders({
      'Content-Type': 'applicantion/json'
    })
  };
  constructor(private _httpHttpClient) {

    console.log('Hello Service Provider');
  }
  UploadFile(_sourceany): Observable<IShowMessage> {
    this._methodName = "UploadFile/";
    this._param = _source;
    return this._http.post<IShowMessage>(
      this._url + this._methodNamethis._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);
            }

        }


       

4 comments: