primeNG 文件上传到字节[]

Sam*_*uaz 3 java hibernate file-upload primeng angular

我如何使用 primeNg fileupload 从文件上传中获取 te byte[] 我需要将其保存在模型中以保留在我的数据库java后端中:在后端我有这个

Class User{

List<UserDocument>

}

class UserDocument{

    @Column(name = "name", length = 100, nullable = false)
    private String name;

    @Column(name = "description", length = 255)
    private String description;

    @Column(name = "type", length = 100, nullable = false)
    private String type;

    @Lob
    @Basic(fetch = FetchType.LAZY)
    @Column(name = "content", nullable = false)
    private byte[] content;

    @ManyToOne(optional = false)
    @JoinColumn(name = "USER_ID")
    private User user;

}
Run Code Online (Sandbox Code Playgroud)

所以在 Angular 6 中我也有用户和用户文档模型,我不需要在用户之前发布上传文件,因为用户此时不存在......

我需要同时创建用户及其使用文档。

所以在角度中我有一个带有用户名filds等的表单,以及primeng文件上传,我所做的是当你上传文件时,我得到事件并从event.files创建一个新的userDocument模型

  onUpload(event) {
    let fileReader = new FileReader();
    for (let file of event.files) {
      const userDocument: UserDocument = new UserDocument();
      userDocument.name = file.name;
      userDocument.description = file.description;
      userDocument.type = file.type;
      userDocument.content = file; /// i need to set here the file byte[]
    }
  }
Run Code Online (Sandbox Code Playgroud)

在角度 userDocument.content 中是一个 any[]

我正在尝试,如何从文件中获取字节[]?

谢谢

use*_*994 6

要获取 BASE64 字符串,您应该执行以下操作:

  onUpload(event) {
    let fileReader = new FileReader();
    for (let file of event.files) {
      fileReader.readAsDataURL(file);
      fileReader.onload = function () {
          // Will print the base64 here.
          console.log(fileReader.result);
      };
    }
  }
Run Code Online (Sandbox Code Playgroud)

或者,如果您希望将数据作为多部分而不是 JSON 发送,您可以执行以下操作:

  onUpload(event) {
    var fd = new FormData();
    for (let file of event.files) {
      fd.append('file', file);
    }
    // POST the data to the backend
    this.http.post(url, fd);
  }
Run Code Online (Sandbox Code Playgroud)

  • 一个小注意事项,如果您需要使用第一种方法访问局部变量(`this.`),请在加载时使用箭头函数`() =&gt; {}`而不是`function () {}`,否则您会赢不在正确的范围内:) (2认同)