Upload Images and save them in a database( Angular 8 + Spring boot + Mysql )

This article is all about uploading an image through your angular project , sending it into the backend and saving it in a database. Not only that, the way how to query the database and viewing back the image in the frontend is also explained here. [As this article is written for explaining the simple mechanism of uploading an image, web page decorations are not done, only the relevant parts are designed for explanation.]

1.0 Frontend
First , create an angular project . ( See how )
We need HttpClientModule for dealing with the backend.So, We
have to import that module to the project.
Go to src/app/app.module.ts

  • Add the following code lines in app.module.ts file as in the image

below.
import { HttpClientModule } from ‘@angular/common/http’;

and, declare the module in imports array.

  • Go to app.component.html file and add the following code.

<h3>Image Uploading Module</h3>

<div>

<input type=”file” (change)=”onFileChanged($event)”>

<img [src]=”imgURL” height=”200″ *ngIf=”imgURL”>

</div>

<! — upload image — >

<input type=”button” (click)=”onUpload()” value=”upload”>

<hr />

Received Image:

{{ receivedImageData[‘pic’] | json}}

<img [src]=”convertedImage” >

The view will be like this.

In this code,
(change)=”onFileChanged($event)
is used to listen to any file choosing event and trigger the onFileChange(event) method in .ts file.

imgURL, convertedImage are properties in the .ts file.

  • Go to src/app/app.component.html file and write the following code snippets in it.

Import HttpClient class from ‘@angular/common/http’ .
And, inject it via the constructor of the class as in the image.

Write and complete your app.component.tsfile as shown in the images.

As the backend is running on local port 8080, posting url is also given as preferred.
We send the image to the backend as a FormData,so that the backend can retrieve it as a multipart file.
By,subscribing to the post method ,we have retrieved the returned image data by the backend and assigned them to the properties which are used to render in the view.

***You may find the code snippets here.