I created a Java Web project that is using JSF with PrimeFaces, Maven, CDI with JPA. My web application is successfully entering the records, the application is a news register, where it is also necessary to insert a photo, the upload approach used is to save the image path in the database.
I was able to complete half of the upload implementation, ie I succeeded in saving the image to the folder, however I could not save the folder path in the database.
It's all working, because of this I'll just put pieces of code to get an idea. Repository Package :
@Inject
private EntityManager manager;
public Noticia guardar(Noticia noticia) {
return manager.merge(noticia);
}
Model package is all mapped correctly with get and set :
private Long id;
private String titulo_noticia;
private Date data_noticia;
private String foto_noticia;
private String desc_noticia;
Controller package:
@Named
@ViewScoped
public class CadastroNoticiaBean implements Serializable {
private static final long serialVersionUID = 1L;
private Noticia noticia;
private Part arquivo;
private String nomeArquivoSaida;
@Inject
private CadastroNoticiaService cadastroNoticiaService;
public CadastroNoticiaBean() {
limpar();
}
public void limpar(){
noticia = new Noticia();
}
public void salvar() {
this.noticia = cadastroNoticiaService.salvar(this.noticia);
upload();
limpar();
FacesUtil.addInfoMessage("Noticia salva com sucesso! ");
}
public void upload() {
nomeArquivoSaida = "C:/workspace Web/Projetos Profissionais/Fotos para teste/" + arquivo.getSubmittedFileName();
try (InputStream is = arquivo.getInputStream();
OutputStream out = new FileOutputStream(nomeArquivoSaida)) {
int read = 0;
byte[] bytes = new byte[1024];
while ((read = is.read(bytes)) != -1) {
out.write(bytes, 0, read);
}
//tentei colocar esse código abaixo para conseguir fazer o insert do caminh do
//banco, mas não tivesse resultado
// preciso muito de ajuda para saber como resolver.
noticia.setFoto_noticia(getNomeArquivoSaida());
} catch (IOException e) {
FacesUtil.addErrorMessage("Erro ao enviar arquivo.");
}
}
public Noticia getNoticia() {
return noticia;
}
public Part getArquivo() {
return arquivo;
}
public void setArquivo(Part arquivo) {
this.arquivo = arquivo;
}
public String getNomeArquivoSaida() {
return nomeArquivoSaida;
}
public void setNomeArquivoSaida(String nomeArquivoSaida) {
this.nomeArquivoSaida = nomeArquivoSaida;
}
}
This is the piece of code on the XHTML page that involves the problem:
<p:outputLabel value="Foto" />
<h:inputFile value="#{cadastroNoticiaBean.arquivo}"/>
I think it's a simple change, I just need to know what it is. I tried a debug test:
The project on GitHub .