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

Entrée/Sortie Java Discussion :

[HttpClient] Upload de fichier avec suivi de l'avancement


Sujet :

Entrée/Sortie Java

Vue hybride

Message précédent Message précédent   Message suivant Message suivant
  1. #1
    Futur Membre du Club
    Profil pro
    Inscrit en
    Juillet 2010
    Messages
    3
    Détails du profil
    Informations personnelles :
    Localisation : Belgique

    Informations forums :
    Inscription : Juillet 2010
    Messages : 3
    Par défaut [HttpClient] Upload de fichier avec suivi de l'avancement
    Bonjour,

    J'utilise la librairie apache HttpClient pour envoyer de gros fichiers en POST.
    HttpClient : package org.apache.commons.httpclient;

    Cependant, j'ai besoin de voir l'avancement de l'upload. Mais je n'y arrive pas.
    J'avais pensé à créer une classe perso et en overritant la méthode write d'un OutputStream utilisé par HttpClient, j'aurais pu intégré mon compteur.

    Pour le moment j'ai ça :

    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
        public void test() throws FileNotFoundException, IOException {
            File file = new File("/home/firone/tmp/Rapport.pdf");
            //File file = new File("/home/firone/mnt/Mon onclde charlie/Mon oncle Charlie - [6x04] - .avi");
     
            final PostMethod pm = new PostMethod("http://firone.firone-land.com/utils/testFile.php");
     
            ArrayList<Part> arrayList = new ArrayList<Part>();
            arrayList.add(new StringPart("hihi", "plop"));
            arrayList.add(new FilePart2("test", file));
            MultipartRequestEntity mre = new MultipartRequestEntity(arrayList.toArray(new Part[]{}), pm.getParams());
     
            pm.setRequestEntity(mre);
     
            final HttpClient hc = new HttpClient();
     
            //OutputStream requestOutputStream = new HttpConnection(hc.getHostConfiguration()).getRequestOutputStream();
     
            System.out.println("5");
     
            Thread thread = new Thread(new Runnable() {
                @Override
                public void run() {
                    try {
                        System.out.println("123");
                        hc.executeMethod(pm);
                        System.out.println(pm.getResponseBodyAsString());
                        System.out.println("234");
                    } catch (IOException ex) {
                        Logger.getLogger(HosterFironeTest.class.getName()).log(Level.SEVERE, null, ex);
                    }
                }
            });
            thread.start();
     
            System.out.println("1");
     
            //OutputStream requestOutputStream = hc.getHttpConnectionManager().getConnection(hc.getHostConfiguration()).getRequestOutputStream();
     
            try {
                thread.join();
            } catch (InterruptedException ex) {
                Logger.getLogger(HosterFironeTest.class.getName()).log(Level.SEVERE, null, ex);
            }
     
            System.out.println("2");
     
        }

  2. #2
    Expert éminent
    Avatar de tchize_
    Homme Profil pro
    Ingénieur développement logiciels
    Inscrit en
    Avril 2007
    Messages
    25 482
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Âge : 46
    Localisation : Belgique

    Informations professionnelles :
    Activité : Ingénieur développement logiciels
    Secteur : High Tech - Éditeur de logiciels

    Informations forums :
    Inscription : Avril 2007
    Messages : 25 482
    Par défaut
    tu pourrais mettre un filtre sur un inputstream pour savoir quelle quantité est lue. ensuite utiliser cet inputstream dans un PartSoruce que tu passerais au final à FilePart. C'est du boulot pour au final ne savoir que ce qui a été lu, pas envoyé. De toutes façons, t'as aucune méthode fiable de savoir ce qui a été envoyé (un proxy intermédiaire peut très bien attendre de tout recevoir avant d'envoyer effectivement au serveur).

  3. #3
    Futur Membre du Club
    Profil pro
    Inscrit en
    Juillet 2010
    Messages
    3
    Détails du profil
    Informations personnelles :
    Localisation : Belgique

    Informations forums :
    Inscription : Juillet 2010
    Messages : 3
    Par défaut
    C'est la première solution que j'ai failli faire, mais ce n'est pas très fiable.
    Depuis hier que j'essaie tout ça ...

    Il n'y a vraiment pas moyen de récupérer le OutputStream utilisé par HttpClient ?
    Mon idée était d'ensuite utiliser une classe de ce genre : (Permettant d'avoir une méthode "getSpeedMeter()" depuis un outputStream classique ...)

    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
    102
    103
    104
    105
    106
    107
    108
    109
    110
    111
    112
    113
    114
    115
    116
    117
    118
    119
    120
    121
    122
    123
    124
    125
    126
    127
    128
    129
    130
    131
    132
    133
    134
    135
    136
    137
    138
    139
    140
    141
    142
    143
    144
    145
    146
    147
    148
    149
    150
    151
    152
    153
    154
    155
    156
    157
    /**
     * Copyright (c) 2009 - 2010 AppWork UG(haftungsbeschränkt) <e-mail@appwork.org>
     * 
     * This file is part of org.appwork.utils.net.meteredconnection
     * 
     * This software is licensed under the Artistic License 2.0,
     * see the LICENSE file or http://www.opensource.org/licenses/artistic-license-2.0.php
     * for details
     */
    package org.appwork.utils.net.meteredconnection;
     
    import java.io.IOException;
    import java.io.OutputStream;
     
    import org.appwork.utils.speedmeter.SpeedMeterInterface;
     
    /**
     * @author daniel
     * 
     */
    public class MeteredOutputStream extends OutputStream implements SpeedMeterInterface {
     
        private OutputStream out;
        private SpeedMeterInterface speedmeter = null;
        private long transfered = 0;
        private long transfered2 = 0;
        private long time = 0;
        private long speed = 0;
        private int offset;
        private int checkStep = 1024;
        // private final static int HIGHStep = 524288;
        public final static int LOWStep = 1024;
        private int rest;
        private int todo;
        private long lastTime;
        private long lastTrans;
        private long timeForCheckStep = 0;
        private int timeCheck = 0;
     
        /**
         * constructor for MeteredOutputStream
         * 
         * @param out
         */
        public MeteredOutputStream(OutputStream out) {
            this.out = out;
        }
     
        /**
         * constructor for MeteredOutputStream with custom SpeedMeter
         * 
         * @param out
         * @param speedmeter
         */
        public MeteredOutputStream(OutputStream out, SpeedMeterInterface speedmeter) {
            this.out = out;
            this.speedmeter = speedmeter;
        }
     
        @Override
        public void write(int b) throws IOException {
            out.write(b);
            transfered++;
        }
     
        public int getCheckStepSize() {
            return checkStep;
        }
     
        public void setCheckStepSize(int step) {
            checkStep = Math.min(LOWStep, checkStep);
        }
     
        @Override
        public void write(byte b[], int off, int len) throws IOException {
            offset = off;
            rest = len;
            while (rest != 0) {
                todo = rest;
                if (todo > checkStep) todo = checkStep;
                timeForCheckStep = System.currentTimeMillis();
                out.write(b, offset, todo);
                timeCheck = (int) (System.currentTimeMillis() - timeForCheckStep);
                if (timeCheck > 1000) {
                    /* we want 2 update per second */
                    checkStep = Math.max(LOWStep, (todo / timeCheck) * 500);
                } else if (timeCheck == 0) {
                    /* we increase in little steps */
                    checkStep += 1024;
                    // checkStep = Math.min(HIGHStep, checkStep + 1024);
                }
                transfered += todo;
                rest -= todo;
                offset += todo;
            }
        }
     
        @Override
        public void flush() throws IOException {
            out.flush();
        }
     
        @Override
        public void close() throws IOException {
            out.close();
        }
     
        /*
         * (non-Javadoc)
         * 
         * @see org.appwork.utils.SpeedMeterInterface#getSpeedMeter()
         */
     
        public synchronized long getSpeedMeter() {
            if (time == 0) {
                time = System.currentTimeMillis();
                transfered2 = transfered;
                return 0;
            }
            if (System.currentTimeMillis() - time < 1000) {
                if (speedmeter != null) return speedmeter.getSpeedMeter();
                return speed;
            }
            lastTime = System.currentTimeMillis() - time;
            time = System.currentTimeMillis();
            lastTrans = transfered - transfered2;
            transfered2 = transfered;
            if (speedmeter != null) {
                speedmeter.putSpeedMeter(lastTrans, lastTime);
                return speedmeter.getSpeedMeter();
            } else {
                speed = (lastTrans / lastTime) * 1000;
                return speed;
            }
        }
     
        /*
         * (non-Javadoc)
         * 
         * @see org.appwork.utils.SpeedMeterInterface#putSpeedMeter(long, long)
         */
        public void putSpeedMeter(long bytes, long time) {
        }
     
        /*
         * (non-Javadoc)
         * 
         * @see org.appwork.utils.SpeedMeterInterface#resetSpeedMeter()
         */
        public synchronized void resetSpeedMeter() {
            if (speedmeter != null) speedmeter.resetSpeedMeter();
            speed = 0;
            transfered2 = transfered;
            time = System.currentTimeMillis();
        }
     
    }

  4. #4
    Futur Membre du Club
    Profil pro
    Inscrit en
    Juillet 2010
    Messages
    3
    Détails du profil
    Informations personnelles :
    Localisation : Belgique

    Informations forums :
    Inscription : Juillet 2010
    Messages : 3
    Par défaut
    Merci pour ta réponse tchize.

    Je n'ai pas trouvé exactement ce que je voulais, mais en héritant une classe de FilePart, on s'en sort pas trop mal. Donc je vais prendre cette solution.

    Pour ceux que ça intéresse :

    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
    /*
     * To change this template, choose Tools | Templates
     * and open the template in the editor.
     */
    package org.apache.commons.httpclient.methods.multipart;
     
    import java.io.File;
    import java.io.FileNotFoundException;
    import java.io.IOException;
    import java.io.InputStream;
    import java.io.OutputStream;
    import org.appwork.utils.net.meteredconnection.MeteredOutputStream;
     
    /**
     *
     * @author firone
     */
    public class MeteredFilePart extends FilePart {
     
        private MeteredOutputStream meteredOutputStream;
     
        public MeteredFilePart(String name, File file) throws FileNotFoundException {
            super(name, file);
        }
     
        public MeteredFilePart(String name, PartSource partSource) {
            super(name, partSource);
        }
     
        public MeteredFilePart(String name, String fileName, File file) throws FileNotFoundException {
            super(name, fileName, file);
        }
     
        public MeteredFilePart(String name, File file, String contentType, String charset) throws FileNotFoundException {
            super(name, file, contentType, charset);
        }
     
        public MeteredFilePart(String name, PartSource partSource, String contentType, String charset) {
            super(name, partSource, contentType, charset);
        }
     
        public MeteredFilePart(String name, String fileName, File file, String contentType, String charset) throws FileNotFoundException {
            super(name, fileName, file, contentType, charset);
        }
     
        /**
         * Write the data in "source" to the specified stream.
         * @param out The output stream.
         * @throws IOException if an IO problem occurs.
         * @see org.apache.commons.httpclient.methods.multipart.Part#sendData(OutputStream)
         */
        @Override
        protected void sendData(OutputStream out) throws IOException {
            if (lengthOfData() == 0) {
     
                // this file contains no data, so there is nothing to send.
                // we don't want to create a zero length buffer as this will
                // cause an infinite loop when reading.
                return;
            }
     
            if (meteredOutputStream == null) {
                out = meteredOutputStream = new MeteredOutputStream(out);
            }
            byte[] tmp = new byte[4096];
            InputStream instream = getSource().createInputStream();
            try {
                int len;
                while ((len = instream.read(tmp)) >= 0) {
                    out.write(tmp, 0, len);
                }
            } finally {
                // we're done with the stream, close it
                instream.close();
            }
     
     
        }
     
        public MeteredOutputStream getMeteredOutputStream() {
            return meteredOutputStream;
        }
    }

Discussions similaires

  1. download et upload des fichier avec JSP & mysql
    Par MSM_007 dans le forum Servlets/JSP
    Réponses: 1
    Dernier message: 17/07/2006, 15h20
  2. Upload de fichier avec jsp
    Par fx2024 dans le forum Servlets/JSP
    Réponses: 2
    Dernier message: 07/06/2006, 17h02
  3. Réponses: 3
    Dernier message: 08/05/2006, 23h31
  4. [Upload] Upload de fichier avec un script PHP
    Par largolgd dans le forum Langage
    Réponses: 7
    Dernier message: 23/04/2006, 15h21
  5. Upload de fichier avec variable passée en paramètre
    Par reservoirdev dans le forum ASP
    Réponses: 2
    Dernier message: 22/04/2006, 16h06

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