简体   繁体   English

primeNG文件上传到字节[]

[英]primeNG fileupload to byte[]

how i can get te byte[] from file upload using the primeNg fileupload i need to save it in a model to persist in my database java backend: in the backend i have this 我如何使用primeNg fileupload从文件上传中获取字节[],我需要将其保存在模型中以保留在数据库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; } 

so in angular 6 i also have the user and userdocuments model, i dont need to post the upload files before the user because the user dont exist at this time... 所以在角度6中我也有用户和用户文档模型,我不需要在用户之前发布上传文件,因为此时用户不存在...

i need to create the user with their usedocuments at same time. 我需要同时使用其usedocument创建用户。

so in angular i have a form with username filds, etc, and the primeng fileupload, what i do is when you upload at file, i get the event and create a new userDocument model from event.files 所以在角度上,我有一个带有用户名filds等的表格,以及primeng fileupload,我要做的就是当您在文件上载时,我得到了事件并从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[]
    }
  }

in angular userDocument.content is a any[] 在有角度的userDocument.content中是any []

im trying, how i can get the byte[] from file? 我正在尝试,如何从文件中获取byte []?

thanks 谢谢

To get the BASE64 string, you should do: 要获取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(reader.result);
      };
    }
  }

Alternately, if you'd rather send the data as multipart instead of JSON, you can do: 或者,如果您希望将数据作为多部分而不是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);
  }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM