Angular 7/8/9 | Input File Image/ File Upload to Base64 Tutorial by Example

Uploading media files like profile images or PDF or Word documents to the server via a web form is a common practice in data-centric applications.

In Angular application where data is sent via HTTP calls, we can easily convert images and docs to the Base64 string and send them to the server is using HTTP Post. After getting the Base64 string we can easily convert it to a real file and save at server disk with file name and path saved in the database.

In this tutorial, we will create Image upload section to select a file and convert it into base64 string without any third part package.

In our method, we will also add a check for images only and width/height limitations to give user appropriate messages for not allowed content.

Let’s start it…

To style the form we are using Bootstrap css which can easily add in the index.html file’s <head> section as shown below:

Now add the following HTML template with form in the component.

The imageError variable is used to show the message to the user if any.  By default the placeholder image will be shown, after the selection of image and conversion to base64 string image will be shown set isImageSaved to true.

In the input file tag, we have added a method fileChangeEvent bind to the (change) event. This method is called after the file is selected by the user.

Next, we will update the component class with the variables and fileChangeEvent method as shown below:

In the fileChangeEvent there are few variables to take values for max file size allowed and max height and width of the uploaded file.

For Other File Type

To enable upload of other file types, just add more to allowed_types array:

 

The uploaded file will be converted to base64 string in the imgBase64Path variable.

To remove the selected image there is also removeImage() method.

Also, we need to put some CSS styles to make it work.

After implementation file upload form will look like this:

 

 

 

 

Leave a Reply

avatar
  Subscribe  
Notify of