【问题标题】:Angular 5 : How can i save a user with a BLOB avatarAngular 5:如何使用 BLOB 头像保存用户
【发布时间】:2019-04-26 18:46:55
【问题描述】:

我是 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:user表中头像字段的类型是longblob

【问题讨论】:

    标签: html angular typescript


    【解决方案1】:

    我不鼓励您将图像保存为数据库中的 blob,最好只保存头像的名称并让图像在之后显示。

    如果您有兴趣尝试,我认为this tutorial 很适合。

    【讨论】:

      【解决方案2】:
      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);
       }
      

      【讨论】:

      • 这对于大文件来说不是很好的做法。对于大文件,使用表单数据将文件放在服务器上
      猜你喜欢
      • 1970-01-01
      • 2022-01-24
      • 2021-10-19
      • 1970-01-01
      • 1970-01-01
      • 2018-09-26
      • 1970-01-01
      • 1970-01-01
      • 2014-03-09
      相关资源
      最近更新 更多