0

我在网上搜索并尝试了我找到的每个示例,但我的示例仍然不起作用。我的 web.xml

...(标题)

<context-param>
    <param-name>javax.faces.PROJECT_STAGE</param-name>
    <param-value>Development</param-value>
</context-param>
<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>/faces/*</url-pattern>
</servlet-mapping>
<servlet-mapping>
    <servlet-name>Faces Servlet</servlet-name>
    <url-pattern>*.xhtml</url-pattern>
</servlet-mapping>
<filter>
    <filter-name>PrimeFaces FileUpload Filter</filter-name>
    <filter-class>org.primefaces.webapp.filter.FileUploadFilter</filter-class>
</filter>
<filter-mapping>
    <filter-name>PrimeFaces FileUpload Filter</filter-name>
    <servlet-name>Faces Servlet</servlet-name>
</filter-mapping>
<listener>
    <listener-class>registration.cleanRegisterDB</listener-class>
</listener>
<listener>
    <listener-class>main.poolChecker</listener-class>
</listener>
<session-config>
    <session-timeout>30</session-timeout>
</session-config>
<welcome-file-list>
    <welcome-file>faces/index.xhtml</welcome-file>
</welcome-file-list>
<listener>
    <listener-class>Utils.SessionAtributeListener.MyAtributeListener</listener-class>
</listener>
<context-param>
    <param-name>primefaces.PRIVATE_CAPTCHA_KEY</param-name>
    <param-value>...</param-value>
</context-param>
<context-param>
    <param-name>primefaces.PUBLIC_CAPTCHA_KEY</param-name>
    <param-value>...</param-value>
</context-param>
<error-page>
    <error-code>404</error-code>
    <location>/faces/404.xhtml</location>
</error-page>

我的 xhtml 页面:

<?xml version='1.0' encoding='UTF-8' ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html 
lang="#{main_bean.authLang()}"
xmlns="http://www.w3.org/1999/xhtml"
xmlns:h="http://java.sun.com/jsf/html"
xmlns:ui="http://java.sun.com/jsf/facelets"
xmlns:p="http://primefaces.org/ui"
xmlns:f="http://java.sun.com/jsf/core"
xmlns:c="http://java.sun.com/jsp/jstl/core">

<f:view locale="#{main_bean.locale}" encoding="ISO-8859-1" >
    <h:head>            
        <h:outputStylesheet library="theme1" name="css/style.css"/>
        <h:outputScript library="theme1" name="js/jquery.validate.js"/>
    </h:head>

    <h:body> 
        <f:event type="preRenderComponent" listener="#{postbean.loadMasterCategories()}" ></f:event>
        <h:panelGroup id="layout-for-image" layout="block">
            <h:link outcome="index.xhtml?faces-redirect=true">
                <h:graphicImage name="theme1/images/logo.png" />
            </h:link>
        </h:panelGroup>

        <h:panelGroup class="layout-titles" layout="block">
            <h2>#{msg.postInt}</h2>
        </h:panelGroup>
        <h:form id="formPostpool" enctype="multipart/form-data" >
            <p:growl id="growlaa" autoUpdate="true"/>
            <p:confirmDialog id="confirmDialog" message="#{msg.dialogConfPostInt}"  
                             header="#{msg.confirmDialogHeader}" severity="alert" widgetVar="confirmation" >  
                <h:panelGroup id="dialog-captcha-layout" layout="block" > 
                    <h:panelGroup layout="block" style="display: inline-block; *display: inline; zoom: 1;">
                        <p:captcha label="Captcha" validatorMessage="#{msg.invalidCaptcha}" required="true" requiredMessage="#{msg.CaptchaNull}" language="#{main_bean.authLang()}"/>
                    </h:panelGroup>
                </h:panelGroup>

                <p:commandButton id="confirm" styleClass="h-button-search" icon="iconDialogYes" actionListener="#{captchaBean.submit}"
                                 action="index" ajax="false" onclick="confirmation.hide();" style="background-image: url('../resources/theme1/images/icons/yes.png')" >
                    <f:actionListener binding="#{postbean.publicatePool()}" />
                </p:commandButton>

                <p:commandButton id="notconfirm" styleClass="h-button-search" icon="iconDialogNo"
                                 ajax="false" type="button" onclick="confirmation.hide();"/> 
            </p:confirmDialog>

            <h:panelGroup class="layout-item-details" layout="block">
                <h2>#{msg.infoProd}</h2>
                <h:panelGroup class="details-element" layout="block">
                    <h:outputLabel value="#{msg.categoryPost}" for="cat"/>
                    <h:panelGroup class="element-inputs" layout="block">
                        <p:selectOneListbox style="height: 150px;" id="cat" value="#{postbean.masterCategoria}" converter="omnifaces.SelectItemsConverter" required="true" requiredMessage="#{msg.message_radiobutton_choose}">
                            <f:selectItems value="#{postbean.categorias}" var="cat" itemLabel="#{cat.descricao}" itemValue="#{cat}" />
                        </p:selectOneListbox>  

                    </h:panelGroup>
                </h:panelGroup>

                <h:panelGroup class="details-element" layout="block">
                    <h:panelGroup class="element-labels" layout="block">
                        <h:outputLabel value="#{msg.titlePost}" for="titulo"/>
                    </h:panelGroup>
                    <h:panelGroup layout="block">
                        <p:inputText id="titulo" value="#{postbean.titulo}" styleClass="inputs-login" required="true" requiredMessage="#{msg.message_titulo_null}"/>
                    </h:panelGroup>
                </h:panelGroup>

                <h:panelGroup class="details-element" layout="block">
                    <h:panelGroup class="element-labels" layout="block">
                        <h:outputLabel value="#{msg.descricaoPost}" for="desc"/>
                    </h:panelGroup>
                    <h:panelGroup layout="block">
                        <p:inputTextarea id="desc" value="#{postbean.descricao}" rows="6" cols="70" styleClass="inputs-textarea" required="true" requiredMessage="#{msg.message_descricao_null}"/>
                    </h:panelGroup>
                </h:panelGroup>

                <h:panelGroup class="details-element" layout="block">
                    <h:panelGroup class="element-labels" layout="block">
                        <h:outputLabel value="#{msg.marcaPost}" for="marca"/>
                    </h:panelGroup>
                    <h:panelGroup layout="block">
                        <p:inputText id="marca" value="#{postbean.marca}" styleClass="inputs-login" />
                    </h:panelGroup>
                </h:panelGroup>

                <h:panelGroup class="details-element" layout="block">
                    <h:panelGroup class="element-labels" layout="block">
                        <h:outputLabel value="#{msg.modeloPost}" for="Modelo"/>
                    </h:panelGroup>
                    <h:panelGroup layout="block">
                        <p:inputText id="Modelo" value="#{postbean.modelo}" styleClass="inputs-login" />
                    </h:panelGroup>
                </h:panelGroup>

                <h:panelGroup class="details-element" layout="block">
                    <h:panelGroup class="element-labels" layout="block">
                        <h:outputLabel value="#{msg.quantidadePost}" for="qtdDesejada"/>
                    </h:panelGroup>
                    <h:panelGroup layout="block">
                        <p:inputText id="qtdDesejada" value="#{postbean.quantidadePretendida}" styleClass="inputs-login" style="width: 100px !important;" required="true" requiredMessage="#{msg.message_quantidade_null}" validatorMessage="#{msg.message_quantidade_invalid}">
                            <f:validateDoubleRange minimum="0.00000001" />
                            <!--<f:validateRegex pattern="([1-9][0-9]*\.?[0-9]*)" for="qtdDesejada" />-->
                        </p:inputText>
                    </h:panelGroup>
                </h:panelGroup>

                <h:panelGroup class="details-element" layout="block">
                    <h:panelGroup class="element-labels" layout="block">
                        <h:outputLabel value="#{msg.precoTargetPost}" for="precoTarget"/>
                    </h:panelGroup>
                    <h:panelGroup layout="block">
                        <p:inputText id="precoTarget" value="#{postbean.preco}" styleClass="inputs-login" style="width: 100px !important;" required="true" requiredMessage="#{msg.message_precoTarget_null}" validatorMessage="#{msg.message_precoTarget_invalid}">
                            <f:validateDoubleRange minimum="0.00000001" />
                        </p:inputText>
                    </h:panelGroup>
                </h:panelGroup>
                <h:panelGroup class="details-element" layout="block">

                    <h:panelGroup class="element-labels" layout="block">
                        <h:outputLabel value="#{msg.fotosPost}" for="foto"/>
                    </h:panelGroup>
                    <!--                        <h:panelGroup layout="block" style="display: inline-block; *display: inline; zoom: 1;" id="addFotoPanel">
                                                <h:inputFile id="idinputFile" value="#{postbean.file}" />
                                            </h:panelGroup>-->
                    <p:fileUpload value="#{postbean.upfile}" auto="true"  fileUploadListener="#{postbean.handleFileUpload}" widgetVar="asd" />

                </h:panelGroup>

                <h:panelGroup class="details-element" layout="block" style="margin-bottom: 15px; width: 250px; padding-left: 175px;">
                    <p:commandButton  id="btn" value="#{msg.label_buttonsubmit}" styleClass="h-button-search" onclick="confirmation.show();"/>
                </h:panelGroup>
            </h:panelGroup>

            <script type="text/javascript">
                                     $(document).ready(function() {
                                         $('#formPostpool').keypress(function(e) {
                                             if (e.keyCode == 13) {
                                                 event.preventDefault();
                                                 $("#btn").click();
                                             }
                                         })
                                     });
            </script>
        </h:form>
    </h:body>
</f:view>

还有 bean: //...一些进口

@ManagedBean(name = "postbean")
@ViewScoped
public class postbean implements Serializable {

//////////////////////////////////
//  FACADES
/////////////////////////////////
@EJB
ProdutoFacade produtofacade = new ProdutoFacade();
@EJB
UsersFacade userfacade = new UsersFacade();
@EJB
ImageFacade imagefacade = new ImageFacade();
@EJB
categoriasFacade categoriafacade = new categoriasFacade();
@EJB
buyerPoolFacade buyerPoolFacade = new buyerPoolFacade();
@EJB
LanguageFacade languageFacade = new LanguageFacade();
@EJB
Lingua_ProdutoFacade langProFacade = new Lingua_ProdutoFacade();
@EJB
MessagesFacade messagesFacade = new MessagesFacade();
/////////////////////////////////////
// VARIAVEIS
////////////////////////////////////
//Destino onde vão ser guardadas as imagens relativas a pool
private String destination = "C:";
private List<String> urls;
private String titulo;
private String descricao;
private String marca;
private String modelo;
private float preco;
private short estado;
private int quantidadePretendida;
private List<categorias> categoria; // lista das categorias
private Timestamp dataActual;
private Users publicationUser;
private categorias masterCategoria;
private categorias option2;
private List<categorias> text;
private List<categorias> subcat2;
private boolean rend;
private boolean rend2;
private Part file;
private UploadedFile upfile;

public Part getFile() {
    return file;
}

public void setFile(Part file) {
    this.file = file;
}

public UploadedFile getUpfile() {
    return upfile;
}

public void setUPfile(UploadedFile upfile) {
    this.upfile = upfile;
}

public postbean() {...}

//...getters and setters

//...some methods

public void handleFileUpload(FileUploadEvent event) {

    ExternalContext externalContext = FacesContext.getCurrentInstance().getExternalContext();
    HttpServletResponse response = (HttpServletResponse) externalContext.getResponse();
    FacesContext ctx = FacesContext.getCurrentInstance();
    Locale l = ctx.getViewRoot().getLocale();
    ResourceBundle rb = ResourceBundle.getBundle("languages.welcome", l);

    FacesContext aFacesContext = FacesContext.getCurrentInstance();
    ServletContext context = (ServletContext) aFacesContext.getExternalContext().getContext();
    try {
        copyFile(event.getFile().getFileName(), event.getFile().getInputstream());
        FacesMessage msg = new FacesMessage(rb.getString("Success"), event.getFile().getFileName() + rb.getString("wasUploaded"));
        FacesContext.getCurrentInstance().addMessage(null, msg);
    } catch (IOException e) {
        e.printStackTrace();
    }
}

public void copyFile(String fileName, InputStream in) {
    String username = userfacade.findUserByIDSessao(FacesUtils.getSessionID());
    OutputStream out = null;
    try {
        // write the inputStream to a FileOutputStream
        File dir = new File(destination + username);
        if (!dir.exists()) {
            dir.mkdir();
        }
        File f = new File(dir + "\\" + fileName);
        out = new FileOutputStream(f);

        int read = 0;
        byte[] bytes = new byte[1024];

        while ((read = in.read(bytes)) != -1) {
            out.write(bytes, 0, read);
        }

        urls.add(username + "//" + f.getName());

        System.out.println("New file created!");
    } catch (IOException e) {
        System.out.println(e.getMessage());
    } finally {
        try {
            in.close();
            out.flush();
            out.close();
        } catch (IOException ex) {
        }
    }
}
//..some methods
}

好吧,我改变了参数,我从 web.xml 文件中删除了过滤器,我改变了 bean...我知道我必须有一个“multipart/form-data”表单,一个 web.xml 文件中的过滤器和一个fileUploader 在 bean 中接收事件。但是什么都没有触发。我单击选择然后上传(如果参数不是 auto="true")并且没有任何反应。我有 commons-io-2.4、commons-fileupload-1.3、primefaces-3.5,我使用 GlassFish Server 4。谢谢!

4

2 回答 2

0
**Note:if you are using Spring-web-flow then it will work**  
 My web.xml file
 *Add this Configuration in web.xml file**

            <filter>
                    <filter-name>PrimeFaces FileUpload Filter</filter-name>
                    <filter-class>org.primefaces.webapp.filter.FileUploadFilter</filter-class>
                </filter>
                <filter-mapping>
                    <filter-name>PrimeFaces FileUpload Filter</filter-name>
                    <servlet-name>Spring MVC Dispatcher Servlet</servlet-name>
                </filter-mapping>

                <servlet>
                    <servlet-name>Spring MVC Dispatcher Servlet</servlet-name>
                    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-    class>
                    <init-param>
                        <param-name>contextConfigLocation</param-name>
                        <param-value></param-value>
                    </init-param>
                    <load-on-startup>2</load-on-startup>
                </servlet>

                <servlet-mapping>
                    <servlet-name>Spring MVC Dispatcher Servlet</servlet- name>
                    <url-pattern>/spring/*</url-pattern>
                </servlet-mapping>

文件上传.xhtml

<html xmlns="http://www.w3.org/1999/xhtml"
    xmlns:h="http://java.sun.com/jsf/html"
    xmlns:f="http://java.sun.com/jsf/core"
    xmlns:ui="http://java.sun.com/jsf/facelets"
    xmlns:p="http://primefaces.org/ui">

 <p:fileUpload id="image"
 fileUploadListener="#{loadFileForm.handleFileUpload}"
mode="advanced" dragDropSupport="true" multiple="true"
update="messages" sizeLimit="100000" fileLimit="3"
allowTypes="/(\.|\/)(xls)$/" />
<p:growl id="messages" showDetail="true" />
</html>

加载文件Bean.java

@ManagedBean(name = "loadFileForm") 公共类 LoadFileFormBean 实现 Serializable {

/**
 * handleFileUpload
 * @param event
 */
public void handleFileUpload(FileUploadEvent event) {
    FacesMessage msg = new FacesMessage("Succesful", event.getFile()
            .getFileName() + " is uploaded.");
    FacesContext.getCurrentInstance().addMessage(null, msg);
}
于 2014-01-11T12:33:59.657 回答
0

我没有尝试过 GlassFish,但发现在 WebLogic 上使用 PrimeFaces 4 我们必须将此参数添加到 web.xml:

<context-param>
    <param-name>primefaces.UPLOADER</param-name>
    <param-value>commons</param-value>
</context-param>

我们正在使用这个 Maven 依赖项:

<dependency>
   <groupId>commons-fileupload</groupId>
   <artifactId>commons-fileupload</artifactId>
   <version>1.3.1</version>
</dependency>

我们还必须确保它PrimeFaces FileUpload Filter是 web.xml 中的第一个过滤器条目。但看起来你的已经是了。

此外,文件上传应该有自己的形式。

于 2015-09-17T23:56:08.247 回答