How To Upload File And Save As Base64 In Angular Using ASP.Net API

How To Upload File And Save As Base64 In Angular Using ASP.Net API

In this article, we will learn how to use the database API to upload a file and save it as Base64. There are various ways to upload and save files; In this article, we will upload a file, base64-encode it, and then use an API to save it to the database. We can use files everywhere in this approach. The file doesn't need to be saved or copied to the server.

So, let's start with the implementation

First, we need to create a new angular application using the following command in the terminal.

ng new angular-file-upload

Now, we need to add HttpClientModule into the app.module.ts file using the 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 { }

Now, add the following code under the app.component.ts file.

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:53780/api/Order/UploadFile`, data)
    .pipe(
      map((res: any) => {
        console.log(res);
        return res;
      }));
  }

}

export class FileUplodVM{
  ImageBaseData: string;
}

To make an API call using the code above, we must import HttpClient and define private http:HttpClient as a function constructor argument. We will save the Image as a Base64 string that we obtain from an uploaded file in the "ImageBaseData" variable, which we shall define.

A function called handleFileInput(files: FileList) was created and will be called whenever the file upload control experiences a change. This function will read the file and write the contents in the ImageBaseData variable as a Base64 string. This variable will be used to display a picture and feed it to the API.

The btnUpload() function will determine whether a file has been selected or not, and if not, it will issue a validation notice. If chosen, the FileUplodVM model will use the ImageBaseData variable and send it to it. afterwards calling the CreateItem(data) method with the FileUplodVM argument.

The CreateItem(data) function will use an API to upload the data.

Now, using the following code add the owl-carousel component under the app.component.html file.

<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 frontend (angular) component is complete. Let me now briefly describe the API (in.NET) and database parts (backend part).

The structure of the database is as follows.

How To Upload File And Save As Base64 In Angular

The code for the .NET API that I used is as follows.

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; }
        }
}

The base64 text for an image will be added to the database by the aforementioned code, and we will receive it in the fileUplodVM.ImageBaseData object that we submit from the angular side. to be saved in the database after that.

That's it; the database now allows you to save images as base64 strings. and employ it whenever you desire. As I used it in the angular app's <img src=""> tag.

Now, run the application using the ng serve command into the terminal and see the browser screen we are able to browse file and save in base64 format using the ASP.Net  API.

How To Upload File And Save As Base64 In Angular


Here is a screenshot of the database once the image has been uploaded.

How To Upload File And Save As Base64 In Angular


Conclusion

In this article, we learned learn how to use the database API to upload a file and save it as Base64 in angular application using the .Net API.

I hope this article helps you and you will like it.👍

Please give your valuable feedback and comments or suggestion in the comment section

If you have any doubt or confusion then free to ask in the comment section.

Post a Comment

Previous Post Next Post