【问题标题】:primeNG fileupload to byte[]primeNG 文件上传到字节 []
【发布时间】:2018-12-23 10:05:26
【问题描述】:

如何使用 primeNg 文件上传从文件上传中获取 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;

}

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

我需要同时使用他们的 usedocuments 创建用户。

所以在 Angular 中,我有一个带有用户名字段等的表单,以及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[]
    }
  }

在 angular userDocument.content 中是 any[]

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

谢谢

【问题讨论】:

  • 您打算如何将数据发送到后端?作为 JSON 对象的一部分?在这种情况下,您将需要一个 BASE64 编码的字符串。或者,如果您的后端接受多部分/forn 编码的数据,最好以该格式发送它
  • 是的,我将在 USER json 对象中发送它,但我需要一种将文件转换为 base64 的方法,是的,后端支持也来自 spring 的 multipartfile

标签: java angular hibernate file-upload primeng


【解决方案1】:

要获取 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);
      };
    }
  }

或者,如果您希望将数据作为多部分而不是 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);
  }

【讨论】:

  • 一个小提示,如果你需要用第一种方法访问局部变量(this.),在onload上使用箭头函数() =&gt; {}而不是function () {},否则你不会在正确的范围内:)
猜你喜欢
  • 1970-01-01
  • 2012-01-21
  • 2019-02-16
  • 1970-01-01
  • 2017-07-23
  • 2013-12-22
  • 1970-01-01
  • 1970-01-01
  • 2013-04-13
相关资源
最近更新 更多