Save Image base 64 AngularJS Spring-Batch

Viewed 67

I need to allow the user to choose a image from his pc, then this image should be save in the database in a blob column. I have this code for select image:

<input type="file" id="fileSelector1" class="form-control" name="schemeupload" accept="image/jpeg" file-model="vm.schemeApply.documents[0]"/>

Then I have to cast the image to base64 for sending to the back(java) and then in the back part insert the base64 string into de blob column? or I have to do in other way? is first time I have to save image.

I know that is not efficient to save image as that but I have to do in that way.

EDIT: I use now this:

<input type="file" id="fileSelector1" class="form-control" name="schemeupload" ng-model="img_icon" file-model as-file accept="image/jpeg" ng-change="onFileSelected(this)" /> 

But I don´t know how to get the img for getting base64 string

1 Answers

This is a plain JavaScript solution without angularjs-file-model demonstrating how to convert a selected file to BASE64. You can take this as a starting point:

function onFileSelected(input) {
    const reader = new FileReader();
    
    reader.addEventListener('load', event => {
        const dataURL = event.target.result;
        
        // Cut away "data:image/png;base64,"
        const base64 = dataURL.substring(dataURL.lastIndexOf(',') + 1);
        console.log(base64);
    });

    reader.addEventListener('error', () => {
        // Error handling code
    })
    
    reader.readAsDataURL(input.files[0]);
}
<input type="file" id="fileSelector1" class="form-control" name="schemeupload" accept="image/jpeg" onchange="onFileSelected(this)">

angularjs-file-model should project the file object into your model when using file-model together with as-file. You might be able to use it here instead of input.files[0].

Related