0
I’m trying to display an image with , but it’s not showing in any browser.
On my page I make the call of the mode image:
<p:graphicImage value="/upload/#{desap.foto}" height="140"
width="140" />
and when I compile and place in inspect element it appears as follows:
src="/ajudeaencontrar/upload/444?pfdrid_c=true"
...Editing
That’s the way my Managedbean is.
@ManagedBean(name = "desapBean")
@SessionScoped
public class CadastroDesaparecidoBean {
private Desaparecido desaparecido;
private DescricaoDesaparecido descricao;
private List<Desaparecido> listaDesaparecido;
private String situacao = null;
// Pega o usuário logado
@ManagedProperty(value = "#{uBean.usuario}")
private Usuario responsavel;
private UploadArquivo arquivo = new UploadArquivo();
private boolean skip;
private boolean isdeficiencia = false;
private boolean booEditar = false;
@PostConstruct
public void inicializar() {
try {
limpar();
listaDesaparecido = new DesaparecidoJPA()
.buscarDesaparecidosPorIdResponsavel2(responsavel);
} catch (Exception e) {
System.out.println("Não foi possível resgatar os dados");
e.printStackTrace();
}
}
public void limpar() {
desaparecido = new Desaparecido();
descricao = new DescricaoDesaparecido();
arquivo = new UploadArquivo();
}
...
/*
* Metodo para realizar o upload de uma foto Os tipos de dados sao validados
* no Primefaces
*/
public void uploadAction(FileUploadEvent event) {
FacesContext fc = FacesContext.getCurrentInstance();
try {
this.arquivo.fileUpload(event, ".jpg");
this.desaparecido.setFoto(this.arquivo.getNome());
fc.addMessage("formcaddesap", new FacesMessage("", event.getFile()
.getFileName() + " foi carregada."));
} catch (Exception ex) {
fc.addMessage("formcaddesap", new FacesMessage("", event.getFile()
.getFileName() + " não foi carregada."));
}
}
public String cadastrar() {
FacesContext fc = FacesContext.getCurrentInstance();
try {
...
new DesaparecidoJPA().gravar(desaparecido);
this.arquivo.gravar();
FacesUtil.addSuccessMessage(desaparecido.getNome()
+ " cadastrado com sucesso.");
System.out.println("arquivo gravado: " + arquivo.getNome());
inicializar();
} catch (Exception e) {
e.printStackTrace();
FacesUtil.addSuccessMessage("Dados não foram armazenados!");
}
return "/admin/painelresp?faces-redirect=true";
}
}
This is the File Upload Class:
public class UploadArquivo {
private String caminho;
private byte[] arquivo;
private String nome;
public UploadArquivo() {
}
public String getNome() {
return nome;
}
public String getRealPath() {
FacesContext aFacesContext = FacesContext.getCurrentInstance();
ServletContext context = (ServletContext) aFacesContext
.getExternalContext().getContext();
//Caminho dentro do projeto no servidor - onde ficarao salvas.
return context.getRealPath("/WEB-INF/upload/");
}
public void fileUpload(FileUploadEvent event, String tipo) throws Exception {
this.nome = new java.util.Date().getTime() + "_"
+ event.getFile().getSize() + tipo;
this.arquivo = event.getFile().getContents();
this.caminho = getRealPath() + getNome();
File file = new File(getRealPath());
file.mkdirs();
System.out.println("caminho: " + caminho);
System.out.println("Nome: " + getNome());
}
public void gravar() {
try {
FileOutputStream fos;
fos = new FileOutputStream(this.caminho);
fos.write(this.arquivo);
fos.close();
} catch (Exception ex) {
System.out.println(ex);
}
}
}
This is the Bean snippet that loads the list to display in Datagrid:
@ManagedBean(name = "api")
@SessionScoped
public class AplicacaoBean {
private Desaparecido desaparecido;
private DescricaoDesaparecido descricao;
private List<Desaparecido> lista;
private List<Desaparecido> resultados = new ArrayList<Desaparecido>();
@PostConstruct
public void inicializar() {
try {
desaparecido = new Desaparecido();
lista = new DesaparecidoJPA().listar();
} catch (Exception e) {
e.printStackTrace();
}
}
public List<Desaparecido> getLista() {
return lista;
}
//Getters and Setters...
The Missing Entity photo attribute is of the String type.
The photo is being recorded correctly on the server, I put to print the path and it shows:
C:\workspace\Java EE SE\.metadata\.plugins\org.eclipse.wst.server.core\tmp2\wtpwebapps\ajudeaencontrar\WEB-INF\upload
Does anyone have any idea how to solve this? I’m willing to display the photo to the user. I’ve looked here on the site, but I can’t find anything specific.
Friend, post the chunk of your bean so that understanding is facilitated.
– Weslley Tavares
Ok, I edited and includes the MB with File Upload.
– Luiz
In the stretch
System.out.println("Nome: " + getNome());
what is printed?– Weslley Tavares
Another thing, this image that you’re trying to visualize, it’s called in another view or it’s still in the same upload view?
– Weslley Tavares
It displays the name that was generated by my rule in the code, the print looks like this:
Nome: 1447176144390_2247.jpg
. Path print example:C:\workspace\Java EE SE\.metadata\.plugins\org.eclipse.wst.server.core\tmp0\wtpwebapps\ajudeaencontrar\WEB-INF\upload1447176144390_2247.jpg
. In BD it only writes the name:1447176144390_2247.jpg
. I try to view in another Sessionscoped view, where the client searches and should be displayed the photo along with the other data.– Luiz
A doubt, in this passage:
src="/ajudeaencontrar/upload/444?pfdrid_c=true"
should not be shown theWEB-INF
also?– Weslley Tavares
In fact I was already doing so, informing the way from the WEB-INF, but it also did not work and I went searching in an example on the web and there was displayed from the directory within the WEB-INF. I changed here in another machine to test, but tbm does not wheel: it was like this:
src="/ajudeaencontrar/WEB-INF/upload/444.jpg?pfdrid_c=true"
– Luiz
Puts the
cache="false"
in your graphicImage– Weslley Tavares
Image does not appear yet, but in html it is now like this:
src="/ajudeaencontrar/WEB-INF/upload/444.jpg?pfdrid_c=false&uid=6ffa29b6-a26d-4fc8-9502-2a981a69979b"
– Luiz
There is this 444.jpg file?
– Weslley Tavares
Pq your bean has the name desapBean and you only call desap.foto in xhtml?
– Weslley Tavares
It is because I am displaying within another view that references the Bean api
<p:dataGrid var="desap" value="#{api.lista}" ...>
. Yes, the files exist and are on the path informed in the print. In my "api" bean I upload a list of an Entity with a String field from the photo. In p:graphicImage I am informing the path + the name of the photo of an object.– Luiz
I put a snippet with the bean "api".
– Luiz
I managed to solve, thanks for the help @Weslleytavares, but I checked an example where the getRealPath() method of my Uploadfile class only returns this way
return context.getRealPath("/");
and not the complete way as I did. Another thing I had to change was the path, I had to take it out of the directory META-INF because it wasn’t working, maybe it’s because I’m using Maven; I put it this way:this.caminho = getRealPath() + "/upload/" + getNome();
and in the call I put so:<h:graphicImage value="./upload/#{desap.foto}">
, where "desap" is my variable for p:datagrid.– Luiz