I'm trying to save the image to disk but it's giving me this error.
mai 18, 2015 12:03:56 PM com.sun.faces.lifecycle.ApplyRequestValuesPhase execute
ADVERTÊNCIA: javax.servlet.ServletException: org.apache.tomcat.util.http.fileupload.FileUploadBase$InvalidContentTypeException: the request doesn't contain a multipart/form-data or multipart/mixed stream, content type header is application/x-www-form-urlencoded;charset=UTF-8
javax.faces.FacesException: javax.servlet.ServletException: org.apache.tomcat.util.http.fileupload.FileUploadBase$InvalidContentTypeException: the request doesn't contain a multipart/form-data or multipart/mixed stream, content type header is application/x-www-form-urlencoded;charset=UTF-8
at org.primefaces.component.fileupload.NativeFileUploadDecoder.decode(NativeFileUploadDecoder.java:44)
at org.primefaces.component.fileupload.FileUploadRenderer.decode(FileUploadRenderer.java:44)
at javax.faces.component.UIComponentBase.decode(UIComponentBase.java:831)
at javax.faces.component.UIInput.decode(UIInput.java:771)
at javax.faces.component.UIComponentBase.processDecodes(UIComponentBase.java:1226)
at javax.faces.component.UIInput.processDecodes(UIInput.java:676)
at org.primefaces.component.api.UIData.process(UIData.java:336)
at org.primefaces.component.api.UIData.processChildren(UIData.java:323)
at org.primefaces.component.api.UIData.processPhase(UIData.java:285)
at org.primefaces.component.api.UIData.processDecodes(UIData.java:245)
at javax.faces.component.UIForm.processDecodes(UIForm.java:225)
at javax.faces.component.UIComponentBase.processDecodes(UIComponentBase.java:1221)
at javax.faces.component.UIComponentBase.processDecodes(UIComponentBase.java:1221)
at org.primefaces.component.layout.Layout.processDecodes(Layout.java:226)
at javax.faces.component.UIComponentBase.processDecodes(UIComponentBase.java:1221)
at javax.faces.component.UIComponentBase.processDecodes(UIComponentBase.java:1221)
at javax.faces.component.UIViewRoot.processDecodes(UIViewRoot.java:929)
at com.sun.faces.lifecycle.ApplyRequestValuesPhase.execute(ApplyRequestValuesPhase.java:78)
at com.sun.faces.lifecycle.Phase.doPhase(Phase.java:101)
at com.sun.faces.lifecycle.LifecycleImpl.execute(LifecycleImpl.java:198)
at javax.faces.webapp.FacesServlet.service(FacesServlet.java:646)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:291)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:239)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:219)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:106)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:501)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:142)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:79)
at org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:610)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:88)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:516)
at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1086)
at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:659)
at org.apache.coyote.http11.Http11NioProtocol$Http11ConnectionHandler.process(Http11NioProtocol.java:223)
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1558)
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.run(NioEndpoint.java:1515)
at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
at java.lang.Thread.run(Unknown Source)
Caused by: javax.servlet.ServletException: org.apache.tomcat.util.http.fileupload.FileUploadBase$InvalidContentTypeException: the request doesn't contain a multipart/form-data or multipart/mixed stream, content type header is application/x-www-form-urlencoded;charset=UTF-8
at org.apache.catalina.connector.Request.parseParts(Request.java:2789)
at org.apache.catalina.connector.Request.getParts(Request.java:2636)
at org.apache.catalina.connector.Request.getPart(Request.java:2813)
at org.apache.catalina.connector.RequestFacade.getPart(RequestFacade.java:1089)
at org.primefaces.component.fileupload.NativeFileUploadDecoder.decodeSimple(NativeFileUploadDecoder.java:50)
at org.primefaces.component.fileupload.NativeFileUploadDecoder.decode(NativeFileUploadDecoder.java:34)
... 42 more
Caused by: org.apache.tomcat.util.http.fileupload.FileUploadBase$InvalidContentTypeException: the request doesn't contain a multipart/form-data or multipart/mixed stream, content type header is application/x-www-form-urlencoded;charset=UTF-8
at org.apache.tomcat.util.http.fileupload.FileUploadBase$FileItemIteratorImpl.<init>(FileUploadBase.java:800)
at org.apache.tomcat.util.http.fileupload.FileUploadBase.getItemIterator(FileUploadBase.java:256)
at org.apache.tomcat.util.http.fileupload.FileUploadBase.parseRequest(FileUploadBase.java:280)
at org.apache.catalina.connector.Request.parseParts(Request.java:2725)
... 47 more
Here's my bean class
package br.com.drogaria.bean;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.Serializable;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import javax.faces.context.FacesContext;
import javax.servlet.ServletContext;
import org.primefaces.model.UploadedFile;
import br.com.drogaria.domain.Produto;
import br.com.drogaria.util.FacesUtil;
import br.com.drogaria.util.Redimensiona;
@ManagedBean
@SessionScoped
public class Fileupload implements Serializable{
/**
*
*/
private static final long serialVersionUID = 1L;
private Produto produtoCadastro;
private UploadedFile arquivo;
public String gravarImagem() {
try {
FacesContext context = FacesContext.getCurrentInstance();
// pega informa��es do contexto para
// conseguir o caminho f�sico
// necess�rio para fazer o upload de arquivo
ServletContext sc = (ServletContext) context.getExternalContext()
.getContext();
// verifica se h� um arquivo para salvar
if (arquivo != null) {
// o tipo de arquivo
String tipoDeArquivo = arquivo.getContentType();
if (tipoDeArquivo.equals("image/jpeg")
|| tipoDeArquivo.equals("image/pjpeg")
|| tipoDeArquivo.equals("image/gif")) {
InputStream stream = arquivo.getInputstream();
int fSize = (int) arquivo.getSize();
byte[] buffer = new byte[(int) fSize];
String nomeArquivo = this.separaNomeImagem(arquivo
.getFileName());
// chama o m�todo que salva o arquivo
Boolean salvarImagem = this.salvarArquivo(buffer, stream,
nomeArquivo, fSize, sc.getRealPath("/imagens"));
if (!salvarImagem) {
FacesUtil.adicionarMsgErro("Problema no upload do arquivo");
}
// cria um thumb se a imagem foi salva
if (salvarImagem) {
// redimensiona a imagem
Boolean salvarThumb = Redimensiona.redimensionar(
nomeArquivo, sc.getRealPath("/imagens"), sc
.getRealPath("/thumbs"), 100, 100, 70);
if (!salvarThumb) {
FacesUtil.adicionarMsgErro("Problema ao salvar o Thumb");
}
}// fim do thumb
produtoCadastro.setImagem(nomeArquivo);
}// fim do if tipoDeArquivo
else {
FacesUtil.adicionarMsgErro("aceito somente JPEG, PJPEG ou GIF.");
}
}
} catch (IOException e) {
FacesUtil.adicionarMsgErro("Um erro ocorreu");
e.printStackTrace();
}
return "sucesso";
}
// salva o arquivo no disco
public boolean salvarArquivo(byte[] buf, InputStream stream,
String nomeArquivo, int size, String path)
throws FileNotFoundException, IOException {
nomeArquivo = this.separaNomeImagem(nomeArquivo);
File file = new File(path + "/" + nomeArquivo);
FileOutputStream output = new FileOutputStream(file);
try {
while (true) {
int count = stream.read(buf, 0, size);
if (count == -1)
break;
output.write(buf, 0, count);
}
} catch (Exception ex) {
ex.printStackTrace();
return false;
}
finally {
output.flush();
output.close();
stream.close();
}
return true;
}
// separa o caminho f�sico do nome do arquivo
private String separaNomeImagem(String nomeImagem) {
if (nomeImagem.lastIndexOf("\") >= -1) {
nomeImagem = nomeImagem.substring(nomeImagem.lastIndexOf("\") + 1);
} else if (nomeImagem.lastIndexOf("/") >= -1) {
nomeImagem = nomeImagem.substring(nomeImagem.lastIndexOf("/") + 1);
}
return nomeImagem;
}
public Produto getProdutoCadastro() {
return produtoCadastro;
}
public void setProdutoCadastro(Produto produtoCadastro) {
this.produtoCadastro = produtoCadastro;
}
public UploadedFile getArquivo() {
return arquivo;
}
public void setArquivo(UploadedFile arquivo) {
this.arquivo = arquivo;
}
}
Here is the page
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:ui="http://java.sun.com/jsf/facelets"
xmlns:h="http://java.sun.com/jsf/html"
xmlns:f="http://java.sun.com/jsf/core"
xmlns:p="http://primefaces.org/ui">
<ui:composition template="/templates/modeloGeral.xhtml">
<ui:define name="metadata">
<f:metadata>
<f:event listener="#{produtoBean.carregarPesquisa}"
type="preRenderView" />
</f:metadata>
</ui:define>
<ui:define name="conteudo">
<h:form>
<p:toolbar>
<f:facet name="left">
<h:outputText value="Produtos" />
</f:facet>
</p:toolbar>
<p:dataTable emptyMessage="Nenhum registro encontrado."
value="#{produtoBean.listaProdutos}"
filteredValue="#{produtoBean.listaProdutosFiltrados}" var="produto"
rows="5" paginator="true">
<f:facet name="footer">
<p:button value="Novo" outcome="/pages/produtoCadastro.xhtml">
<f:param name="proacao" value="Novo" />
</p:button>
</f:facet>
<p:column headerText="Código">
<h:outputText value="#{produto.codigo}" />
</p:column>
<p:column headerText="Descrição" filterBy="#{produto.descricao}"
sortBy="#{produto.descricao}">
<h:outputText value="#{produto.descricao}" />
</p:column>
<p:column headerText="Preço" sortBy="#{produto.preco}">
<h:outputText value="#{produto.preco}">
<f:convertNumber type="currency" currencySymbol="R$" />
</h:outputText>
</p:column>
<p:column headerText="Quantidade">
<h:outputText value="#{produto.quantidade}" />
</p:column>
<p:column headerText="Opções">
<p:button value="Excluir" outcome="/pages/produtoCadastro.xhtml">
<f:param name="procod" value="#{produto.codigo}" />
<f:param name="proacao" value="Excluir" />
</p:button>
<p:button value="Editar" outcome="/pages/produtoCadastro.xhtml">
<f:param name="procod" value="#{produto.codigo}" />
<f:param name="proacao" value="Editar" />
</p:button>
</p:column>
<p:column>
<p:fileUpload value="#{fileupload.arquivo}" mode="simple"
update="growl" />
<p:commandButton value="Procurar" action="#{fileupload.produtoCadastro}">
<f:ajax execute="@all" render="@form"/>
</p:commandButton>
</p:column>
</p:dataTable>
</h:form>
</ui:define>
</ui:composition>
</html>
here is my Web.xml file
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
id="WebApp_ID" version="3.1">
<display-name>Drogaria</display-name>
<welcome-file-list>
<welcome-file>pages/principal.xhtml</welcome-file>
</welcome-file-list>
<servlet>
<servlet-name>Faces Servlet</servlet-name>
<servlet-class>javax.faces.webapp.FacesServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>Faces Servlet</servlet-name>
<url-pattern>*.xhtml</url-pattern>
</servlet-mapping>
<listener>
<listener-class>br.com.drogaria.util.ContextListener</listener-class>
</listener>
</web-app>
I wanted to know why you are giving the error message, and I would like to correct and solve the problem.