Angular

How To Upload File And Save As Base64 In Angular 9

In this article, we will learn about how to upload a file and save as Base64 into the database using API.

there are many different ways to upload and save files, in this article we will upload and convert that file in base64 and then save it in the database using API. this way we can use files anywhere. we don’t need to save or copy the file on the server.

Prerequisites:

  • Basic knowledge of Angular
  • Code editor like Visual Studio Code

Create a new Angular project by typing the following command in the VSCode terminal.

ng new FileUploadProject

Open the app.module.ts file and import HttpClientModule in it. as we are going to call API or making HTTP call for posting data. Please refer following code.

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
import {FormsModule} from '@angular/forms'; 
import { HttpClientModule } from "@angular/common/http";

@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
    BrowserModule,
    AppRoutingModule,
    FormsModule,
    HttpClientModule,
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }

Open the app.component.ts file and add the following code in it.

import { Component } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { map } from 'rxjs/operators';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  title = 'FileUploadProject';
  ImageBaseData:string | ArrayBuffer=null;

  constructor(private http:HttpClient) {

  }

  handleFileInput(files: FileList) {
    let me = this;
    let file = files[0];
    let reader = new FileReader();
    reader.readAsDataURL(file);
    reader.onload = function () {
      console.log(reader.result);
      me.ImageBaseData=reader.result;
    };
    reader.onerror = function (error) {
      console.log('Error: ', error);
    };
 }

  btnUpload(){
    
    if(this.ImageBaseData==null){
      alert("Please select file");
    }else{     
      var fileUplodVM: FileUplodVM={
        ImageBaseData:this.ImageBaseData.toString()
      }

      this.CreateItem(fileUplodVM).subscribe((res: any) =>{ 
        if(res){
          alert("Successfully uploded file");
        }else{
          alert("File upload failed");
        }
        
      },
      error => {
        alert(error.message);
      });
    }

  }

  public CreateItem(data) {
   return this.http.post(`http://localhost:52410/api/Order/UploadFile`, data)
    .pipe(
      map((res: any) => {
        console.log(res);
        return res;
      }));
  }

}

export class FileUplodVM{
  ImageBaseData: string;
}

in the above code, we need to import HttpClient for making an API call and define private http:HttpClient as a parameter in the constructor. define the “ImageBaseData” variable in which we will store Image as Base64 string that we will get from an uploaded file.

made one function handleFileInput(files: FileList) which is going to call on change event of file upload control. this function will read the file and store it in the Base64 string in ImageBaseData variable. we will use this variable for displaying an image and passing to API.

Function btnUpload() will check if a file is selected or not, if not then it will give validation alert. if selected then it will use ImageBaseData variable and pass/use it in FileUplodVM model. and then call CreateItem(data) function by passing FileUplodVM as parameter.

CreateItem(data) Function will post data using API.

Now, open the app.component.html and add the following code in it.

<h2>File Upload</h2>
  <!-- <p>Here are some links to help you get started:</p> -->

    <div class="card-container">
    <input type="file" id="FUImage" name="FUImage" accept=".png, .jpg, .jpeg" (change)="handleFileInput($event.target.files)"> 
    <button type="button" class="btn btn-danger pull-left" (click)="btnUpload()">Upload</button> 
  </div>
  <div class="card-container">
    <img src="{{ImageBaseData}}" alt="Selected Image" height="200" width="200">
  </div>

your angular (frontend) part is ready. now let me give you a short description of API(in .NET)  and database part (backend part).

The following is a database structure.

 

 

 

The following is code for .Net API which I have used.

public class OrderController : ApiController
{
        OrderManagmentDBEntities Db = new OrderManagmentDBEntities();

        public HttpResponseMessage UploadFile([FromBody]FileUplodVM fileUplodVM)
        {
            try
            {
                TblDemoImage tblDemoImage = new TblDemoImage
                {
                    ImageBaseData = fileUplodVM.ImageBaseData
                };
                Db.TblDemoImage.Add(tblDemoImage);
                Db.SaveChanges();

                return Request.CreateResponse(HttpStatusCode.OK, true, Configuration.Formatters.JsonFormatter);
            }
            catch (Exception ex)
            {
                return Request.CreateResponse(HttpStatusCode.OK, false, Configuration.Formatters.JsonFormatter);
            }
        }

        public partial class FileUplodVM
        {
            public string ImageBaseData { get; set; }
        }
}

above code will add an image as base64 string in the database, we will get base64 string in fileUplodVM.ImageBaseData object which we post from the angular side. and then save it in the database.

that’s it, now you can save image as base64 string in the database. and use it whenever you want to use it. as I used it in <img src=””> tag directly in this angular app.

The following is the image of the Angular app.

following is a screenshot of the database after uploading the image.

so this is one way of uploading a file in the database.

Angular.js developers can help you build scalable, secure, and innovative web applications. To build online apps for startups and corporations, our dedicated Angularjs engineers employ the best tools available.  Hire Angular developers in India who can provide you with the best support and maintenance services that are tailored to your company’s needs. We ensure that Angular.js development services are promoted and that your apps’ overall performance is improved.

you may also like this article on angular.

  1. Angular 9 Is Now Available
  2. How To Bind DropDownList From API With Validation In Angular
Tabish Rangrej

Tabish Rangrej is an Experienced .NET Team Leader, software engineer, and Author with a demonstrated history of working in the IT industry. He has quite well experience in developing, communicating, managing, and writing in his field. He has strong skills and knowledge of ASP.NET C#, ASP.NET MVC, ASP.NET CORE, Angular, AngularJS, Web API, SQL, Entity Framework, JavaScript, Jquery, Different Integrations like Quickbooks, Stripe, Google APIs, Zoho, Orion, Xero, etc., Different versioning tools like TFS, SVN, GIT, etc. and Windows services. Strong engineering professional with a Master of Computer Applications - MCA focused on Computer Science from Veer Narmad South Gujarat University, Surat. Tabish is always ready to accept new challenges and learn new things, he would like to serve better for the community.

Recent Posts

Testing hk

Testing

2 years ago

Create and Used PIPE in angular

In this article, we have to show Create and Used PIPE in angular

2 years ago

Operation

Testing

2 years ago

Create and Used PIPE in angular

In this article, we have to show Create and Used PIPE in angular

2 years ago

Create and Used PIPE in angular

In this article, we have to show Create and Used PIPE in angular

2 years ago

TETS NEW

test

2 years ago