IdentifiantMot de passe
Loading...
Mot de passe oublié ?Je m'inscris ! (gratuit)
Navigation

Inscrivez-vous gratuitement
pour pouvoir participer, suivre les réponses en temps réel, voter pour les messages, poser vos propres questions et recevoir la newsletter

Java EE Discussion :

Upload et Download


Sujet :

Java EE

Vue hybride

Message précédent Message précédent   Message suivant Message suivant
  1. #1
    Membre averti
    Homme Profil pro
    Étudiant
    Inscrit en
    Avril 2011
    Messages
    45
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : France

    Informations professionnelles :
    Activité : Étudiant

    Informations forums :
    Inscription : Avril 2011
    Messages : 45
    Par défaut Upload et Download
    Bonjour,

    Je souhaite dans ma page JSF télécharger des fichiers situés dans le dossier "documents" et uploader des fichiers dans ce même dossier.
    Pour cela j'ai la page JSF suivante :

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
                Télécharger des documents :<br/>
                <h:dataTable value="#{tacheDetailBean.tache.documents}" var="document" id="tableDocuments">
                    <h:column>
                        <h:form id="form">
                            <p:commandButton id="downloadLink" value="#{document.nom} (#{document.user.prenom} #{document.user.nom})" ajax="false" onclick="PrimeFaces.monitorDownload(start, stop)" icon="ui-icon-arrowthichk-s">  
                                <p:fileDownload value="#{downloadBean.file}" />  
                            </p:commandButton> 
                        </h:form>
                    </h:column>
                </h:dataTable>
                <br/>
                Uploader des fichiers :<br/>
                <p:fileUpload fileUploadListener="#{uploadBean.upload}" allowTypes="/(\.|\/)(gif|jpe?g|png|pdf)$/" sizeLimit="100000"/>
    Ainsi que les 2 beans suivants :

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    package control;
     
    import java.io.File;
    import java.io.FileOutputStream;
    import java.io.IOException;
    import java.io.InputStream;
    import java.io.OutputStream;
    import java.io.Serializable;
    import javax.enterprise.context.SessionScoped;
     
    import javax.faces.application.FacesMessage;
    import javax.faces.context.FacesContext;
    import javax.inject.Named;
     
    import org.primefaces.event.FileUploadEvent;
     
    @Named
    @SessionScoped
    public class UploadBean implements Serializable {
     
        public void upload(FileUploadEvent event) {
            FacesMessage msg = new FacesMessage("Success! ", event.getFile().getFileName() + " is uploaded.");
            FacesContext.getCurrentInstance().addMessage(null, msg);
            // Do what you want with the file        
            try {
                copyFile(event.getFile().getFileName(), event.getFile().getInputstream());
            } catch (IOException e) {
                e.printStackTrace();
            }
     
        }
     
        public void copyFile(String fileName, InputStream in) {
            try {
     
                // write the inputStream to a FileOutputStream
                OutputStream out = new FileOutputStream(new File("./documents/" + fileName));
     
                int read = 0;
                byte[] bytes = new byte[1024];
     
                while ((read = in.read(bytes)) != -1) {
                    out.write(bytes, 0, read);
                }
     
                in.close();
                out.flush();
                out.close();
     
                System.out.println("New file created!");
            } catch (IOException e) {
                System.out.println(e.getMessage());
            }
        }
    }
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    package control;
     
    import java.io.InputStream;
    import javax.faces.context.FacesContext;
    import javax.servlet.ServletContext;
     
    import org.primefaces.model.DefaultStreamedContent;
    import org.primefaces.model.StreamedContent;
     
    public class DownloadBean {
     
        private final StreamedContent file;
     
        public DownloadBean() {
            InputStream stream = ((ServletContext) FacesContext.getCurrentInstance().getExternalContext().getContext()).getResourceAsStream("/documents/logofcm.png");
            file = new DefaultStreamedContent(stream, "image/png", "logofcm.png");
        }
     
        public StreamedContent getFile() {
            return file;
        }
    }
    Le téléchargement me donne une nullpointerexception et l'upload ne fait rien.

    Merci d'avance pour votre aide.

    Vivien

  2. #2
    Traductrice
    Avatar de Mishulyna
    Femme Profil pro
    Développeur Java
    Inscrit en
    Novembre 2008
    Messages
    1 505
    Détails du profil
    Informations personnelles :
    Sexe : Femme
    Localisation : Belgique

    Informations professionnelles :
    Activité : Développeur Java
    Secteur : High Tech - Éditeur de logiciels

    Informations forums :
    Inscription : Novembre 2008
    Messages : 1 505
    Par défaut
    Pour que ça fasse ce que tu veux il faudrait donner un chemin absolu du fichier, genre "C:/Users/Toi/Documents/ImagesApp/logofcm.png"

    Si ce n'est pas encore fait (et en fonction de la structure de ton projet), ajoute ceci à ton fichier web.xml
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    <filter>
            <filter-name>PrimeFaces FileUpload Filter</filter-name>
            <filter-class>
                org.primefaces.webapp.filter.FileUploadFilter
            </filter-class>
            <init-param>
                <param-name>thresholdSize</param-name>
                <param-value>51200</param-value>
            </init-param>
            <init-param>
                <param-name>uploadDirectory</param-name>
                <param-value>C:\temp</param-value>
            </init-param>
        </filter>
     
        <filter-mapping>
            <filter-name>PrimeFaces FileUpload Filter</filter-name>
            <servlet-name>Faces Servlet</servlet-name>
        </filter-mapping>
    Par précaution, crée toi-même un dossier "temp" sous C:.

  3. #3
    Membre averti
    Homme Profil pro
    Étudiant
    Inscrit en
    Avril 2011
    Messages
    45
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : France

    Informations professionnelles :
    Activité : Étudiant

    Informations forums :
    Inscription : Avril 2011
    Messages : 45
    Par défaut
    Merci de votre réponse, cependant pas de changement voici mon web.xml :
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    <?xml version="1.0" encoding="UTF-8"?>
    <web-app version="3.1" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd">
        <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>
        <filter>
            <filter-name>PrimeFaces FileUpload Filter</filter-name>
            <filter-class>
                org.primefaces.webapp.filter.FileUploadFilter
            </filter-class>
            <init-param>
                <param-name>thresholdSize</param-name>
                <param-value>51200</param-value>
            </init-param>
            <init-param>
                <param-name>uploadDirectory</param-name>
                <param-value>/Users/vivientouly/NetBeansProjects/projetJEE/src/main/webapp/resources/documents</param-value>
            </init-param>
        </filter>
     
        <filter-mapping>
            <filter-name>PrimeFaces FileUpload Filter</filter-name>
            <servlet-name>Faces Servlet</servlet-name>
        </filter-mapping>
        <session-config>
            <session-timeout>
                30
            </session-timeout>
        </session-config>
        <welcome-file-list>
            <welcome-file>faces/login.xhtml</welcome-file>
        </welcome-file-list>
    </web-app>

  4. #4
    Traductrice
    Avatar de Mishulyna
    Femme Profil pro
    Développeur Java
    Inscrit en
    Novembre 2008
    Messages
    1 505
    Détails du profil
    Informations personnelles :
    Sexe : Femme
    Localisation : Belgique

    Informations professionnelles :
    Activité : Développeur Java
    Secteur : High Tech - Éditeur de logiciels

    Informations forums :
    Inscription : Novembre 2008
    Messages : 1 505
    Par défaut
    Avez-vous modifié les chemins de fichier dans les classes UploadBean et DownloadBean? Je ne comprends pas trop pourquoi vous utilisez deux beans... Commencez par faire simple, par exemple recopier une image d'un dossier à l'autre. UploadBean devrait suffire pour cela.

    Si ça ne marche toujours pas: merci de mettre le contenu du fichier log contenant les erreurs.

  5. #5
    Membre averti
    Homme Profil pro
    Étudiant
    Inscrit en
    Avril 2011
    Messages
    45
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : France

    Informations professionnelles :
    Activité : Étudiant

    Informations forums :
    Inscription : Avril 2011
    Messages : 45
    Par défaut
    J'ai changé mes classes en me basant sur le site de primefaces, mais ça ne fonctionne toujours pas, voilà ce que j'ai :

    tache.xml :
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    67
    68
    69
    70
    71
    72
    73
    74
    75
    76
    77
    78
    79
    80
    81
    82
    83
    84
    85
    86
    87
    88
    89
    90
    91
    92
    93
    94
    95
    96
    97
    98
    99
    100
    101
    <?xml version='1.0' encoding='UTF-8' ?>
    <!DOCTYPE composition PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
    <ui:composition 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="http://www.w3.org/1999/xhtml"
                    template="./template.xhtml"
                    xmlns:p="http://primefaces.org/ui">
     
     
        <ui:define name="content">
     
            <f:metadata>
                <f:viewParam name="tache" value="#{tacheDetailBean.pid}"/>
                <f:event type="javax.faces.event.PreRenderComponentEvent" listener="#{tacheDetailBean.loadTache()}"/>
                <f:event type="javax.faces.event.PreRenderComponentEvent" listener="#{tacheDetailBean.chaineEtat()}"/>
            </f:metadata>
            <h:form>
                <center><h2>#{tacheDetailBean.tache.nom}</h2></center>
                <br/>
     
                <div class="row">
                    <div class="span6">
                        <b>Responsable :</b> #{tacheDetailBean.tache.responsable.prenom} #{tacheDetailBean.tache.responsable.nom}
                        <br/><br/>
                        <b>Début :</b> #{tacheDetailBean.tache.dateCreation}
                        <br/>
                        <b>Fin :</b> #{tacheDetailBean.tache.dateEcheance}
                    </div>
                    <div class="span6">
                        <i>Tâche #{tacheDetailBean.etat}</i>
                        <br/><br/>
                        <b>Description :</b>
                        <br/>
                        #{tacheDetailBean.tache.description}
                        <br/><br/>
                        <b>Participants :</b>
                        <br/>
                        <h:dataTable value="#{tacheDetailBean.tache.participants}" var="participant" id="tableParticipants">
                            <h:column>
                                #{participant.prenom} #{participant.nom}
                            </h:column>
                        </h:dataTable>
                    </div>
                </div>
     
                <br/>
                <b>Timeline :</b>
                <br/>
                <h:dataTable value="#{tacheDetailBean.tache.timeline}" var="message" id="tableTimeline">
                    <h:column>
                        #{message.contenu}
                        <br/>
                        <i>#{message.user.prenom} #{message.user.nom}, le #{message.dateMessage}</i>
                        <br/>
                    </h:column>
                </h:dataTable>
     
                <h:inputText id="newMessage" value="#{messageBean.message.contenu}" size="100"/>
                <br/>       
                <h:commandButton value="Commenter" action="#{messageBean.nouveauMessage}"/>
     
                <br/>
                <br/> 
            </h:form>
     
            <h4>Télécharger un document :</h4>
            <br/>
            <p:dialog modal="true" widgetVar="statusDialog" header="Status" draggable="false" closable="false" resizable="false">
                <p:graphicImage value="/design/ajaxloadingbar.gif" />
            </p:dialog>
     
            <h:form id="form">
                <p:commandButton id="downloadLink" value="Télécharger" ajax="false" onclick="PrimeFaces.monitorDownload(start, stop)" icon="ui-icon-arrowthichk-s">
                    <p:fileDownload value="#{fileDownloadController.file}" />
                </p:commandButton>
            </h:form>
     
            <script type="text/javascript">
                function start() {
                    PF('statusDialog').show();
                }
     
                function stop() {
                    PF('statusDialog').hide();
                }
            </script>
            <br/>
     
            <h4>Uploader un document :</h4>
            <br/>
            <h:form enctype="multipart/form-data">
                <p:messages showDetail="true"/>
                <p:fileUpload value="#{fileUploadController.file}" mode="simple"/>
                <p:commandButton value="Envoyer le document" ajax="false" actionListener="#{fileUploadController.upload}"/>
            </h:form>
     
        </ui:define>
     
     
    </ui:composition>
    FileUploadController.java :
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    package control;
     
    import javax.faces.application.FacesMessage;
    import javax.faces.context.FacesContext;
     
    import org.primefaces.model.UploadedFile;
     
    public class FileUploadController {
     
        private UploadedFile file;
     
        public UploadedFile getFile() {
            return file;
        }
     
        public void setFile(UploadedFile file) {
            this.file = file;
        }
     
        public void upload() {
            if(file != null) {
                FacesMessage msg = new FacesMessage("Succesful", file.getFileName() + " is uploaded.");
                FacesContext.getCurrentInstance().addMessage(null, msg);
            }
        }
    }
    FileDownloadController.java :
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    package control;
     
    import java.io.InputStream;
    import javax.faces.context.FacesContext;
    import javax.servlet.ServletContext;
     
    import org.primefaces.model.DefaultStreamedContent;
    import org.primefaces.model.StreamedContent;
     
    public class FileDownloadController {
     
    	private StreamedContent file;
     
    	public FileDownloadController() {        
            InputStream stream = ((ServletContext)FacesContext.getCurrentInstance().getExternalContext().getContext()).getResourceAsStream("/Users/vivientouly/NetBeansProjects/projetJEE/src/main/webapp/resources/documents/logofcm.png");
    		file = new DefaultStreamedContent(stream, "image/png", "logofcm.png");
    	}
     
        public StreamedContent getFile() {
            return file;
        }  
    }
    web.xml :
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    <?xml version="1.0" encoding="UTF-8"?>
    <web-app version="3.1" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd">
        <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>
        <filter>
            <filter-name>PrimeFaces FileUpload Filter</filter-name>
            <filter-class>
                org.primefaces.webapp.filter.FileUploadFilter
            </filter-class>
            <init-param>
                <param-name>thresholdSize</param-name>
                <param-value>51200</param-value>
            </init-param>
            <init-param>
                <param-name>uploadDirectory</param-name>
                <param-value>/Users/vivientouly/NetBeansProjects/projetJEE/src/main/webapp/resources/documents</param-value>
            </init-param>
        </filter>
     
        <filter-mapping>
            <filter-name>PrimeFaces FileUpload Filter</filter-name>
            <servlet-name>Faces Servlet</servlet-name>
        </filter-mapping>
        <session-config>
            <session-timeout>
                30
            </session-timeout>
        </session-config>
        <welcome-file-list>
            <welcome-file>faces/login.xhtml</welcome-file>
        </welcome-file-list>
    </web-app>
    Pour le téléchargement rien ne se passe lorsque je clique sur le bouton et pour l'upload j'ai cette erreur de NullPointerException :
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    java.lang.NullPointerException
    	at org.primefaces.component.fileupload.FileUploadRenderer.decodeSimple(FileUploadRenderer.java:56)
    	at org.primefaces.component.fileupload.FileUploadRenderer.decode(FileUploadRenderer.java:47)
    	at javax.faces.component.UIComponentBase.decode(UIComponentBase.java:836)
    	at javax.faces.component.UIInput.decode(UIInput.java:771)
    	at javax.faces.component.UIComponentBase.processDecodes(UIComponentBase.java:1228)
    	at javax.faces.component.UIInput.processDecodes(UIInput.java:676)
    	at javax.faces.component.UIForm.processDecodes(UIForm.java:225)
    	at javax.faces.component.UIComponentBase.processDecodes(UIComponentBase.java:1223)
    	at javax.faces.component.UIComponentBase.processDecodes(UIComponentBase.java:1223)
    	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.StandardWrapper.service(StandardWrapper.java:1682)
    	at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:344)
    	at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:214)
    	at org.primefaces.webapp.filter.FileUploadFilter.doFilter(FileUploadFilter.java:77)
    	at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:256)
    	at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:214)
    	at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:316)
    	at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:160)
    	at org.apache.catalina.core.StandardPipeline.doInvoke(StandardPipeline.java:734)
    	at org.apache.catalina.core.StandardPipeline.invoke(StandardPipeline.java:673)
    	at com.sun.enterprise.web.WebPipeline.invoke(WebPipeline.java:99)
    	at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:174)
    	at org.apache.catalina.connector.CoyoteAdapter.doService(CoyoteAdapter.java:357)
    	at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:260)
    	at com.sun.enterprise.v3.services.impl.ContainerMapper.service(ContainerMapper.java:188)
    	at org.glassfish.grizzly.http.server.HttpHandler.runService(HttpHandler.java:191)
    	at org.glassfish.grizzly.http.server.HttpHandler.doHandle(HttpHandler.java:168)
    	at org.glassfish.grizzly.http.server.HttpServerFilter.handleRead(HttpServerFilter.java:189)
    	at org.glassfish.grizzly.filterchain.ExecutorResolver$9.execute(ExecutorResolver.java:119)
    	at org.glassfish.grizzly.filterchain.DefaultFilterChain.executeFilter(DefaultFilterChain.java:288)
    	at org.glassfish.grizzly.filterchain.DefaultFilterChain.executeChainPart(DefaultFilterChain.java:206)
    	at org.glassfish.grizzly.filterchain.DefaultFilterChain.execute(DefaultFilterChain.java:136)
    	at org.glassfish.grizzly.filterchain.DefaultFilterChain.process(DefaultFilterChain.java:114)
    	at org.glassfish.grizzly.ProcessorExecutor.execute(ProcessorExecutor.java:77)
    	at org.glassfish.grizzly.nio.transport.TCPNIOTransport.fireIOEvent(TCPNIOTransport.java:838)
    	at org.glassfish.grizzly.strategies.AbstractIOStrategy.fireIOEvent(AbstractIOStrategy.java:113)
    	at org.glassfish.grizzly.strategies.WorkerThreadIOStrategy.run0(WorkerThreadIOStrategy.java:115)
    	at org.glassfish.grizzly.strategies.WorkerThreadIOStrategy.access$100(WorkerThreadIOStrategy.java:55)
    	at org.glassfish.grizzly.strategies.WorkerThreadIOStrategy$WorkerThreadRunnable.run(WorkerThreadIOStrategy.java:135)
    	at org.glassfish.grizzly.threadpool.AbstractThreadPool$Worker.doWork(AbstractThreadPool.java:564)
    	at org.glassfish.grizzly.threadpool.AbstractThreadPool$Worker.run(AbstractThreadPool.java:544)
    	at java.lang.Thread.run(Thread.java:744)

  6. #6
    Traductrice
    Avatar de Mishulyna
    Femme Profil pro
    Développeur Java
    Inscrit en
    Novembre 2008
    Messages
    1 505
    Détails du profil
    Informations personnelles :
    Sexe : Femme
    Localisation : Belgique

    Informations professionnelles :
    Activité : Développeur Java
    Secteur : High Tech - Éditeur de logiciels

    Informations forums :
    Inscription : Novembre 2008
    Messages : 1 505
    Par défaut Upload
    Bonjour,

    Pour l'upload je vous propose les modifications suivantes:
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    public void handleFileUpload(FileUploadEvent event) {
            InputStream is;
            String fileName = event.getFile().getFileName();
            String absoluteDestination = "C:\\testUpload\\destination\\"; // si cette destination n'existe pas vous la créez ou la modifiez selon vos besoins 
     
            try {
                File tempFile = new File(absoluteDestination + fileName);
                System.out.print("tempFile " + tempFile.getAbsolutePath()); // test
                is = event.getFile().getInputstream();
                OutputStream os = new FileOutputStream(tempFile);
     
                byte buf[] = new byte[1024];
                int len;
                while ((len = is.read(buf)) > 0) {
                    os.write(buf, 0, len);
                }
                os.close();
                is.close();
     
                System.out.print("fileName" + fileName);//test
     
            } catch (IOException ex) {
                ex.printStackTrace();
            }
            FacesMessage msg = new FacesMessage("Succesful", event.getFile().getFileName() + " is uploaded.");
            FacesContext.getCurrentInstance().addMessage(null, msg);
        }
    Pour le download:
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    public FileDownloadController() {  
            // j'ai créé un dossier "images" dans le dossier Web Pages du projet et j'ai mis une image de taille appropriée dedans...
            InputStream stream = ((ServletContext) FacesContext.getCurrentInstance().getExternalContext().getContext()).getResourceAsStream("/images/monimage.jpg"); 
            file = new DefaultStreamedContent(stream, "image/jpg", "downloaded_monimage.jpg"); // vous allez choisir où vous voulez mettre l'image. Le plus facile ça a été sur Bureau
        }
    Bonus: outil pour générer vos propres ajax.gif.

Discussions similaires

  1. programme pour upload et download (urgent)
    Par samunta dans le forum Servlets/JSP
    Réponses: 1
    Dernier message: 24/02/2009, 10h28
  2. Problème de Upload et Download de fichiers
    Par bard123 dans le forum JSF
    Réponses: 11
    Dernier message: 27/05/2008, 10h57
  3. [Upload] le download des fichiers
    Par gabi27685 dans le forum Langage
    Réponses: 3
    Dernier message: 28/03/2008, 15h55
  4. FileReference et gestion des upload et download
    Par Watier_53 dans le forum ActionScript 3
    Réponses: 1
    Dernier message: 05/03/2008, 09h58
  5. Upload et download de fichier sans utiliser JSP
    Par RR instinct dans le forum Langage
    Réponses: 8
    Dernier message: 30/08/2006, 12h08

Partager

Partager
  • Envoyer la discussion sur Viadeo
  • Envoyer la discussion sur Twitter
  • Envoyer la discussion sur Google
  • Envoyer la discussion sur Facebook
  • Envoyer la discussion sur Digg
  • Envoyer la discussion sur Delicious
  • Envoyer la discussion sur MySpace
  • Envoyer la discussion sur Yahoo