1
votes

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

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...

i need to create the user with their usedocuments at same time.

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

  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[]

im trying, how i can get the byte[] from file?

thanks

1
How do you intend to send the data to the backend? As part of a JSON object? In that case you will need a BASE64 encoded string. Alternately, if your backend accepts multipart/forn-encoded data, it may be better to send it in that format - user184994
yes i will send it in USER json object, but i need a way to covert the file to base64, and yes the backend support also multipartfile from spring - Samuaz

1 Answers

2
votes

To get the BASE64 string, you should do:

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

Alternately, if you'd rather send the data as multipart instead of JSON, you can do:

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