How to save an upload file to the database with Primefaces

Asked

Viewed 338 times

0

I searched a little about uploading files with primefaces and couldn’t find any example of code that saved a file in the database.

You can save a file as if it were a class attribute?

2 answers

0

I advise never saving byte array in database, in the future if you need to make a backup your database will be huge, instead use solutions like S3 from Amazon, we work this way in several solutions and has always been the best choice adopted.

the code change will be simple, instead of playing in an entity create a service that saves the file in S3, and then save the link generated in your register.

0

It gives yes, you have to save a byte array of the file. I used in the example below the component of the primefaces (http://primefaces.org/showcase/ui/file/upload/single.xhtml) as a reference:

Entity: public class Pessoa { private Integer idPessoa; private String nome; private byte[] foto; //get e set }

Managedbean:

@ManagedBean(name = "pessoaMB") @SessionScoped public class PessoaMB { private Pessoa pessoa; private StreamedContent foto; @PostConstruct public void postConstruct() { this.pessoa = new Pessoa(); } public void handleFileUpload(FileUploadEvent event) { try { this.pessoa.setFoto(event.getFile().getContents()); this.foto = new DefaultStreamedContent(event.getFile().getInputstream()); FacesMessage message = new FacesMessage("Sucesso", event.getFile().getFileName() + " foi carregada."); FacesContext.getCurrentInstance().addMessage(null, message); } catch (IOException e) { e.printStackTrace(); } } public Pessoa getPessoa() { return pessoa; } public void setPessoa(Pessoa pessoa) { this.pessoa = pessoa; } public StreamedContent getFoto() { return foto; } }

Browser other questions tagged

You are not signed in. Login or sign up in order to post.