user10497113
user10497113

Reputation: 27

Angular 5 : How can i save a user with a BLOB avatar

I'm a newbie on Angular and i want to save a new user with an avatar, so how can i pass the Blob value of the avatar to my user Model so i can save it properly?

This is my code :

HTML

<input type="file" (change)="onSelectFile($event)" accept="image/x-png,image/gif,image/jpeg" value="{{image}}" id="avatar" ngModel name="avatar" #avatar="ngModel"/>

Typescript

image:any;

onSelectFile(event) {
  var reader ;
  reader = new FileReader;
  reader.onload = (event) => {
    console.log(reader.result);
    this.image = reader.result;
    console.log(this.image);
  }
  reader.readAsDataURL(event.target.files[0]);
}

The error i get when saving the user:

{"timestamp":"2018-11-24T13:29:13.222+0000","status":400,"error":"Bad Request","message":"JSON parse error: Cannot deserialize value of type `byte[]` from String \"\\fakepath\\IMG_20180808_023905.jpg\": Failed to decode VALUE_STRING as base64 (MIME-NO-LINEFEEDS): Illegal character ':' (code 0x3a) in base64 content; nested exception is com.fasterxml.jackson.databind.exc.InvalidFormatException: Cannot deserialize value of type `byte[]` from String \"\\fakepath\\IMG_20180808_023905.jpg\": Failed to decode VALUE_STRING as base64 (MIME-NO-LINEFEEDS): Illegal character ':' (code 0x3a) in base64 content\n at [Source: (PushbackInputStream); line: 1, column: 134] (through reference chain: org.vi.entities.User[\"avatar\"])","path":"/users"}

PS: the type of avatar field in user table is longblob

Upvotes: 0

Views: 925

Answers (2)

Sadmi
Sadmi

Reputation: 361

I don't encourage you to save images as blobs in the database, it's better to save just the name of the avatar and get the image to show after.

if you are interested in trying that I think this tutorial is good for that.

Upvotes: 1

Michael
Michael

Reputation: 94

onSelectFile(event) {
    let reader = new FileReader;
    reader.onload = this.handle.bind(this); 
    reader.readAsArrayBuffer(this.file);
}

handle(readerEvt: any) {

   let bytes = new Uint8Array(readerEvt.target.result);
   for (let index = 0; index < bytes.byteLength; index++) {
       this.image += String.fromCharCode(bytes[index]);
    }
 }

it is better idea to write images as text in database and send base64 string to server. Then your function should look like this:

handle(readerEvt: any) {

   let bytes = new Uint8Array(readerEvt.target.result);
   let binaryText = ''; 
   for (let index = 0; index < bytes.byteLength; index++) {
       let binaryText += String.fromCharCode(bytes[index]);
    }
   this.image = btoa(binaryText);
 }

Upvotes: 0

Related Questions