Angular 5:如何使用BLOB头像保存用户

时间:2018-11-24 13:50:48

标签: html angular typescript

我是Angular的新手,我想用化身保存一个新用户,那么如何将化身的Blob值传递给我的用户模型,以便我可以正确保存它?

这是我的代码:

HTML

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

打字稿

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

保存用户时出现的错误:

{"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:用户表中的头像字段类型为longblob

2 个答案:

答案 0 :(得分:1)

我不鼓励您将图像另存为blob,最好只保存化身的名称并在以后显示图像。

如果您有兴趣尝试使用this tutorial对此很有帮助。

答案 1 :(得分:0)

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

最好将图像以文本形式写入数据库,然后将base64字符串发送到服务器。 然后您的函数应如下所示:

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