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

Langage PHP Discussion :

[Upload] upload fichier sur ftp free


Sujet :

Langage PHP

  1. #41
    Membre actif
    Avatar de jak0
    Profil pro
    Inscrit en
    Mai 2005
    Messages
    272
    Détails du profil
    Informations personnelles :
    Localisation : France

    Informations forums :
    Inscription : Mai 2005
    Messages : 272
    Points : 219
    Points
    219
    Par défaut
    Si tu lance Internet Explorer, dans Outils tu doit avoir Console Java (Sun), ca te permet aussi d'accéder à la console.

    Peut-être à tu un problème d'installation de la JRE.
    Est-ce que dans le dossier d'installation du JDK tu a un dossier jre ?
    Goah Sha Kree

  2. #42
    Membre du Club
    Profil pro
    Inscrit en
    Septembre 2002
    Messages
    87
    Détails du profil
    Informations personnelles :
    Localisation : France

    Informations forums :
    Inscription : Septembre 2002
    Messages : 87
    Points : 68
    Points
    68
    Par défaut
    En activant la console, j'ai bien la tasse de café qui apparaît (et oui, il y a bien un dossier JRE dans le JDK... il y a même J2RE installé !)
    Par contre, lorsque j'ouvre le formulaire html, aucune erreur ne semble s'inscrire sur la console, à part :

    Plug-in Java(TM): Version 1.4.2_10
    Utilisation de la version JRE 1.4.2_10 Java HotSpot(TM) Client VM
    Répertoire d'accueil de l'utilisateur = C:\Documents and Settings\Administrateur

    Configuration du proxy : Aucun proxy
    ... suivi du lexique de java, avec tous les raccourcis des commandes.

  3. #43
    Membre actif
    Avatar de jak0
    Profil pro
    Inscrit en
    Mai 2005
    Messages
    272
    Détails du profil
    Informations personnelles :
    Localisation : France

    Informations forums :
    Inscription : Mai 2005
    Messages : 272
    Points : 219
    Points
    219
    Par défaut
    Tu utilise Firefox ou Internet Explorer pour voir ta page HTML ?
    Si c'est firefox, il faut que le plugin Java soit installé dessus...

    J'ai du mal à comprendre le problème, peut-tu donné des précisions, sur la facon d'appeler la page, la config de java et du navigateur? merci.
    Goah Sha Kree

  4. #44
    Membre du Club
    Profil pro
    Inscrit en
    Septembre 2002
    Messages
    87
    Détails du profil
    Informations personnelles :
    Localisation : France

    Informations forums :
    Inscription : Septembre 2002
    Messages : 87
    Points : 68
    Points
    68
    Par défaut
    Alors, j'ai firefox et IE installés sur mon ordi.
    Je n'avais pas pensé à tester firefox, et je viens de le faire .
    Cette fois ci, à la place de l'applet java, je n'ai plus la croix rouge, mais un rectangle gris.
    Dans la barre des tâches, il est dit :

    Echec de chargement de l'applet java.
    De plus, cette fois-ci , la tasse de café apparait automatiquement.
    Quand j'ouvre la console, le message d'erreur est le suivant :

    charger : classe Uploader.class introuvable.

    java.lang.ClassNotFoundException: Uploader.class

    at sun.applet.AppletClassLoader.findClass(Unknown Source)

    at java.lang.ClassLoader.loadClass(Unknown Source)

    at sun.applet.AppletClassLoader.loadClass(Unknown Source)

    at java.lang.ClassLoader.loadClass(Unknown Source)

    at sun.applet.AppletClassLoader.loadCode(Unknown Source)

    at sun.applet.AppletPanel.createApplet(Unknown Source)

    at sun.plugin.AppletViewer.createApplet(Unknown Source)

    at sun.applet.AppletPanel.runLoader(Unknown Source)

    at sun.applet.AppletPanel.run(Unknown Source)

    at java.lang.Thread.run(Unknown Source)

    Caused by: java.io.IOException: open HTTP connection failed.

    at sun.applet.AppletClassLoader.getBytes(Unknown Source)

    at sun.applet.AppletClassLoader.access$100(Unknown Source)

    at sun.applet.AppletClassLoader$1.run(Unknown Source)

    at java.security.AccessController.doPrivileged(Native Method)

    ... 10 more

    Je te résume en gros ce que j'ai fait depuis le début :

    J'ai créé un formulaire avec ton code html.
    Puis j'ai créé 3 fichiers avec l'extension .java à partir des autres codes que tu m'as filé.
    Enfin, j'ai ajouté le FTPconnection.java (de la faq) dans le même dossier.
    Avec Netbeans, j'ai ensuite généré un Uploader.jar, que j'ai signé.

    J'ai ensuite uploadé le Uploader.jar et le formulaire html sur mon FTP...

  5. #45
    Membre actif
    Avatar de jak0
    Profil pro
    Inscrit en
    Mai 2005
    Messages
    272
    Détails du profil
    Informations personnelles :
    Localisation : France

    Informations forums :
    Inscription : Mai 2005
    Messages : 272
    Points : 219
    Points
    219
    Par défaut
    charger : classe Uploader.class introuvable.
    signifie que la machine java n'arrive pas a trouver le fichier a executer. J'ai verifier le code HTML que je t'ai filé, et en fait, j'ai laissé un truc qu'il ne fallait pas lol.

    Dans ta balise object tu as un parametre : En fait ca correspond au dossier où se trouve le Uploader.jar.

    Si ton Uploader.jar et ton fichier HTML sont dans le même dossier, alors vire ce paramêtre, et normalement, ça devrait marcher...

    PS : J'ai fait une nouvelle version de cet outils. Maintenant que tu l'a fait une fois, si tu te sent près, je pourrais te filer le nouveau code (qui inclus le suivi du téléchargement : barre de progression + taille envoyé), tu devrait arriver a recompiler, a resigner, et a republier, non ? lol
    Goah Sha Kree

  6. #46
    Membre actif
    Avatar de jak0
    Profil pro
    Inscrit en
    Mai 2005
    Messages
    272
    Détails du profil
    Informations personnelles :
    Localisation : France

    Informations forums :
    Inscription : Mai 2005
    Messages : 272
    Points : 219
    Points
    219
    Par défaut
    Citation Envoyé par pepper
    Super ! J'attends la suite ....
    Par contre, est-ce que le login et le MDP seront visibles dans la source du code ?
    En fait je viens de comprendre ce que tu voulais réellement dire par là lol.
    Et la réponse est non, car les utilisateurs n'auront que des fichiers .class, fichiers qui ne sont pas visualisables...
    Et si tu as ton propre serveur (je sais que ce n'est pas le cas), tu peut créer un utilisateurs aux droits très limités, ça rajoutera une sécurité...
    Goah Sha Kree

  7. #47
    Membre du Club
    Profil pro
    Inscrit en
    Septembre 2002
    Messages
    87
    Détails du profil
    Informations personnelles :
    Localisation : France

    Informations forums :
    Inscription : Septembre 2002
    Messages : 87
    Points : 68
    Points
    68
    Par défaut
    Alors, j'ai viré le "source" de la balise object, et il me propose maintenant d'accepter l'applet.
    Je dis "oui", mais j'ai toujours une erreur dans la console java (rien ne se charge de plus) :

    java.lang.UnsupportedClassVersionError: Uploader (Unsupported major.minor version 49.0)

    at java.lang.ClassLoader.defineClass0(Native Method)

    at java.lang.ClassLoader.defineClass(Unknown Source)

    at java.security.SecureClassLoader.defineClass(Unknown Source)

    at java.net.URLClassLoader.defineClass(Unknown Source)

    at java.net.URLClassLoader.access$100(Unknown Source)

    at java.net.URLClassLoader$1.run(Unknown Source)

    at java.security.AccessController.doPrivileged(Native Method)

    at java.net.URLClassLoader.findClass(Unknown Source)

    at sun.applet.AppletClassLoader.findClass(Unknown Source)

    at java.lang.ClassLoader.loadClass(Unknown Source)

    at sun.applet.AppletClassLoader.loadClass(Unknown Source)

    at java.lang.ClassLoader.loadClass(Unknown Source)

    at sun.applet.AppletClassLoader.loadCode(Unknown Source)

    at sun.applet.AppletPanel.createApplet(Unknown Source)

    at sun.plugin.AppletViewer.createApplet(Unknown Source)

    at sun.applet.AppletPanel.runLoader(Unknown Source)

    at sun.applet.AppletPanel.run(Unknown Source)

    at java.lang.Thread.run(Unknown Source)

  8. #48
    Membre actif
    Avatar de jak0
    Profil pro
    Inscrit en
    Mai 2005
    Messages
    272
    Détails du profil
    Informations personnelles :
    Localisation : France

    Informations forums :
    Inscription : Mai 2005
    Messages : 272
    Points : 219
    Points
    219
    Par défaut
    Décidement ...

    java.lang.UnsupportedClassVersionError: Uploader (Unsupported major.minor version 49.0)
    Veut dire que la version de java utilisé pour la comilation du code java (JDK) est supérieur à celle utilisé pour exécuter java (JRE).

    Je pense que tu devait avoir une JRE installé avant, et que ton navigateur utilise celle la au lieu de prendre la nouvelle, il faut donc que tu regarde dans les proprietes de ton navigateur ou de ta jre dans le panneau de config...

    Par contre, perso je me suis fait chié a telecharger la version juste anterieure : 1.4.2 pour permettre aux gens dont java nest pas totalement a jour, dexecuter lapplet...

    Au pire, tas juste a faire un clic droit sur la tasse de café et a la mettre a jour...
    Goah Sha Kree

  9. #49
    Membre du Club
    Profil pro
    Inscrit en
    Septembre 2002
    Messages
    87
    Détails du profil
    Informations personnelles :
    Localisation : France

    Informations forums :
    Inscription : Septembre 2002
    Messages : 87
    Points : 68
    Points
    68
    Par défaut
    Bon, alors, je crois bien que ça marche !!!
    J'ai essayé avec un fichier de plus de 3 Mo, et il n'y a pas eu de souci.
    Je vais tout de même refaire l'applet avec un JDK antérieur comme tu me l'as conseillé.

    Du coup, les deux premiers input du html ne servent à rien, tout se joue avec le bouton "Transférer avec Java" !?

    Euh, sinon, je voulais être sûr : pour l'utlisateur lambda, qu'est-ce que ça implique d'arriver sur une page avec une applet java ... il va devoir comprendre lui-même qu'il faut installer java, ou alors, ça s'installe automatiquement (avec juste une confirmation) ?

    Enfin, cela m'intéresse assez de voir la nouvelle version de ton code !

  10. #50
    Membre actif
    Avatar de jak0
    Profil pro
    Inscrit en
    Mai 2005
    Messages
    272
    Détails du profil
    Informations personnelles :
    Localisation : France

    Informations forums :
    Inscription : Mai 2005
    Messages : 272
    Points : 219
    Points
    219
    Par défaut
    Pour l'installation, ça dépend du navigateur et de sa version. Firefox 1.5 doit pouvoir installer le plugin tout seul, les versions antérieures ne le permettent pas, mais affiche un message d'information.

    Pour IE, je sais pas trop, mais il doit affiché un message, après est-ce qu'il peut l'installer, j'en sais rien.

    Et les deux input servent en fait à envoyé par http le nom du fichier qui a été uploader par ftp, afin de pouvoir le retrouver dans ton script php et de le traîter comme il se doit.

    Pour la nouvelle version, je te prépare ça...
    Goah Sha Kree

  11. #51
    Membre du Club
    Profil pro
    Inscrit en
    Septembre 2002
    Messages
    87
    Détails du profil
    Informations personnelles :
    Localisation : France

    Informations forums :
    Inscription : Septembre 2002
    Messages : 87
    Points : 68
    Points
    68
    Par défaut
    Bien noté ... je te remercie pour ces précisions !

  12. #52
    Membre actif
    Avatar de jak0
    Profil pro
    Inscrit en
    Mai 2005
    Messages
    272
    Détails du profil
    Informations personnelles :
    Localisation : France

    Informations forums :
    Inscription : Mai 2005
    Messages : 272
    Points : 219
    Points
    219
    Par défaut
    Je te conseil donc de bien uploader les fichiers dans un dossier spécifique, car imagine que l'utilisateur upload un fichier nommé index.php à la racine de ton site, tu serai bien embêté...
    De plus, question sécurité (dossier inconnu de l'utilisateur), c'est assez utile...
    Goah Sha Kree

  13. #53
    Membre actif
    Avatar de jak0
    Profil pro
    Inscrit en
    Mai 2005
    Messages
    272
    Détails du profil
    Informations personnelles :
    Localisation : France

    Informations forums :
    Inscription : Mai 2005
    Messages : 272
    Points : 219
    Points
    219
    Par défaut
    Alors, tu en est où ? tout marche correctement ???
    Je te file la derniere version dès que tu me dis que tout est bon...
    Goah Sha Kree

  14. #54
    Membre du Club
    Profil pro
    Inscrit en
    Septembre 2002
    Messages
    87
    Détails du profil
    Informations personnelles :
    Localisation : France

    Informations forums :
    Inscription : Septembre 2002
    Messages : 87
    Points : 68
    Points
    68
    Par défaut
    Eh bien, à vrai dire, avec Firefox, ça semble marcher.
    Il faut juste que j'installe une version un peu plus ancienne de java pour que ça marche pour chaque utilisateur ...

  15. #55
    Membre actif
    Avatar de jak0
    Profil pro
    Inscrit en
    Mai 2005
    Messages
    272
    Détails du profil
    Informations personnelles :
    Localisation : France

    Informations forums :
    Inscription : Mai 2005
    Messages : 272
    Points : 219
    Points
    219
    Par défaut
    Oue si tu veut, mais la 1.4.2, c'est déjà pas la toute derniere, et plus tu utilise des versions anciennes de Java moins c'est puissant et sécurisé. Enfin après c'est toi qui voit.

    Bon maintenant que tout marche nickel, tu es prêt à recommencer les manip avec une nouvelle version ? lol
    Goah Sha Kree

  16. #56
    Membre du Club
    Profil pro
    Inscrit en
    Septembre 2002
    Messages
    87
    Détails du profil
    Informations personnelles :
    Localisation : France

    Informations forums :
    Inscription : Septembre 2002
    Messages : 87
    Points : 68
    Points
    68
    Par défaut
    Ben, maintenant que le baptême a été fait, pas de problèmes, allons-y !!

  17. #57
    Membre actif
    Avatar de jak0
    Profil pro
    Inscrit en
    Mai 2005
    Messages
    272
    Détails du profil
    Informations personnelles :
    Localisation : France

    Informations forums :
    Inscription : Mai 2005
    Messages : 272
    Points : 219
    Points
    219
    Par défaut
    Fichier ThreadUpload.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
    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
    import java.io.File;
    import java.io.IOException;
    import java.net.UnknownHostException;
    import javax.swing.JLabel;
     
    public class ThreadUpload extends Thread {
     
        private Transfert parent = null;
        private FTPConnection connection = null;
        private int sendedSize = 0;
        private String destination_name = null;
     
        public ThreadUpload(String name, Transfert parent) {
            super(name);
            this.parent = parent;
        }
     
        public String getDestinationName() {
            return this.destination_name;
        }
     
        public void run() {
     
            this.connection = new FTPConnection(this);
            try {
                if (this.connection.connect("xxx.xxx.xxx.xxx")) {
                    if (this.connection.login("xxxxxxx", "xxxxxxx")) {
                        if (this.connection.getCurrentDirectory() != null) {
                            this.destination_name = this.parent.getFile().getName();
                            System.out.println("Transfert du fichier:" + this.destination_name + ";");
                            this.destination_name = this.destination_name.replaceAll(" ",   "_");
                            this.destination_name = this.destination_name.replaceAll("\\?", "_");
                            this.destination_name = this.destination_name.replaceAll("\\*", "_");
                            this.destination_name = this.destination_name.replaceAll("&",   "_");
                            this.destination_name = this.destination_name.replaceAll("\\^", "_");
                            this.destination_name = this.destination_name.replaceAll("\\%", "_");
                            this.destination_name = this.destination_name.replaceAll("\\$", "_");
                            this.destination_name = this.destination_name.replaceAll("#",   "_");
                            if (!connection.uploadFile("/"+this.destination_name, this.parent.getFile().getPath())) {
                                throw new IOException ("Erreur de transfert incconue");
                            }
                            System.out.println("Transfert terminé.");
     
                            this.parent.finalizeUpload(true);
                        } else {
                            System.out.println("Erreur FTP001 de connexion rencontré, fichier non transféré.");
                            this.parent.getLabel().setText("Erreur de connexion rencontré, fichier non transféré.");
                            this.parent.finalizeUpload(false);
                        }
                    } else {
                        System.out.println("Erreur FTP002 de connexion rencontré, fichier non transféré.");
                        this.parent.getLabel().setText("Erreur de connexion rencontré, fichier non transféré.");
                        this.parent.finalizeUpload(false);
                    }
                    this.connection.disconnect();
                }
            } catch (UnknownHostException e) {
                System.out.println("Erreur : "+e);
                System.out.println("Erreur de connexion rencontré, fichier non transféré.");
                this.parent.getLabel().setText("Erreur de connexion rencontré, fichier non transféré.");
                this.parent.finalizeUpload(false);
            } catch (IOException e) {
                System.out.println("Erreur : "+e);
                System.out.println("Erreur de connexion rencontré, fichier non transféré.");
                this.parent.getLabel().setText("Erreur de transfert rencontré, fichier non transféré.");
                this.parent.finalizeUpload(false);
            }
        }
     
        public void stopThread () {
            try {
                this.connection.forceDisconnect();
            } catch (NullPointerException e) { }
            this.stop();
        }
     
        public void setUncontrolTransfert() {
            this.parent.setUncontrolTransfert();
        }
     
        public File getFile() {
            return this.parent.getFile();
        }
     
        public JLabel getLabel() {
            return this.parent.getLabel();
        }
     
        public void finalizeUpload(boolean flag) {
            this.parent.finalizeUpload(flag);
        }
     
        public void setStatus(int status) {
            this.sendedSize += status;
            this.parent.setStatus(this.sendedSize);
        }
     
    }
    Goah Sha Kree

  18. #58
    Membre actif
    Avatar de jak0
    Profil pro
    Inscrit en
    Mai 2005
    Messages
    272
    Détails du profil
    Informations personnelles :
    Localisation : France

    Informations forums :
    Inscription : Mai 2005
    Messages : 272
    Points : 219
    Points
    219
    Par défaut
    Fichier Transfert.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
    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
    158
    159
    160
    161
    162
    163
    164
    165
    166
    167
    168
    169
    170
    171
    172
    173
    174
    175
    176
    177
    178
    179
    180
    181
    182
    183
    184
    185
    186
    187
    188
    189
    190
    191
    192
    193
    194
    195
    196
    197
    198
    199
    200
    201
    202
    203
    204
    205
    206
    207
    208
    209
    210
    211
    212
    213
    214
    215
    216
    217
    218
    219
    220
    221
    222
    223
    224
    225
    226
    227
    228
    229
    230
    231
    232
    233
    234
    235
    236
    237
    238
    239
    240
    241
    242
    243
    244
    245
    246
    247
    248
    249
    250
    251
    252
    253
    254
    255
    256
    257
    258
    259
    260
    261
    262
    263
    264
    265
    import java.io.File;
    import java.io.IOException;
    import java.net.UnknownHostException;
    import java.security.AccessControlException;
    import javax.swing.JFileChooser;
    import javax.swing.JFrame;
    import javax.swing.JLabel;
    import javax.swing.JProgressBar;
     
    public class Transfert extends javax.swing.JFrame {
     
        private Uploader parent;
        private ThreadUpload thread;
        private boolean isok = false;
        private File file;
        private boolean finish = false;
        private boolean transfert = false;
     
        public Transfert(Uploader parent) {
            super("Transfert de fichier");
            this.parent = parent;
            initComponents();
            this.btnOk.setEnabled(false);
            this.btnStop.setEnabled(false);
            this.progress.setIndeterminate(false);
            this.progress.setMinimum(0);
            this.progress.setMaximum(100);
            this.progress.setValue(0);
        }
     
        private void initComponents() {
            btnOpen = new javax.swing.JButton();
            btnOk = new javax.swing.JButton();
            pnlTransfert = new javax.swing.JPanel();
            progress = new javax.swing.JProgressBar();
            pnlCompteurs = new javax.swing.JPanel();
            lblPercent = new javax.swing.JLabel();
            lblSize = new javax.swing.JLabel();
            pnlHaut = new javax.swing.JPanel();
            label = new javax.swing.JLabel();
            btnStop = new javax.swing.JButton();
     
            setDefaultCloseOperation(javax.swing.WindowConstants.DO_NOTHING_ON_CLOSE);
            addWindowListener(new java.awt.event.WindowAdapter() {
                public void windowClosing(java.awt.event.WindowEvent evt) {
                    exit(evt);
                }
            });
     
            btnOpen.setText("Parcourir");
            btnOpen.addActionListener(new java.awt.event.ActionListener() {
                public void actionPerformed(java.awt.event.ActionEvent evt) {
                    openFile(evt);
                }
            });
     
            getContentPane().add(btnOpen, java.awt.BorderLayout.WEST);
     
            btnOk.setText("Lancer");
            btnOk.addActionListener(new java.awt.event.ActionListener() {
                public void actionPerformed(java.awt.event.ActionEvent evt) {
                    launchTransfert(evt);
                }
            });
     
            getContentPane().add(btnOk, java.awt.BorderLayout.EAST);
     
            pnlTransfert.setLayout(new java.awt.GridLayout(2, 0));
     
            pnlTransfert.add(progress);
     
            pnlCompteurs.setLayout(new java.awt.BorderLayout());
     
            lblPercent.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
            lblPercent.setText("00 %");
            lblPercent.setPreferredSize(new java.awt.Dimension(50, 20));
            pnlCompteurs.add(lblPercent, java.awt.BorderLayout.WEST);
     
            lblSize.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
            lblSize.setText("Taille : ");
            pnlCompteurs.add(lblSize, java.awt.BorderLayout.CENTER);
     
            pnlTransfert.add(pnlCompteurs);
     
            getContentPane().add(pnlTransfert, java.awt.BorderLayout.CENTER);
     
            pnlHaut.setLayout(new java.awt.BorderLayout());
     
            pnlHaut.setPreferredSize(new java.awt.Dimension(150, 40));
            label.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
            label.setText("Veuillez s\u00e9lectionner votre fichier.");
            label.setPreferredSize(new java.awt.Dimension(50, 35));
            pnlHaut.add(label, java.awt.BorderLayout.CENTER);
     
            btnStop.setText("Stop");
            btnStop.setPreferredSize(new java.awt.Dimension(67, 23));
            btnStop.addActionListener(new java.awt.event.ActionListener() {
                public void actionPerformed(java.awt.event.ActionEvent evt) {
                    btnStopActionPerformed(evt);
                }
            });
     
            pnlHaut.add(btnStop, java.awt.BorderLayout.EAST);
     
            getContentPane().add(pnlHaut, java.awt.BorderLayout.NORTH);
     
            java.awt.Dimension screenSize = java.awt.Toolkit.getDefaultToolkit().getScreenSize();
            setBounds((screenSize.width-400)/2, (screenSize.height-110)/2, 400, 110);
        }
     
        private void btnStopActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnStopActionPerformed
            this.setVisible(false);
            System.out.println("on arrete le transfert, et on reinitalise l'applet");
            try { this.thread.stopThread(); } catch (NullPointerException e) { }
            this.parent.reinitUpload();
            this.thread = null;
        }
     
        private void exit(java.awt.event.WindowEvent evt) {
            exit();
        }
     
        private void launchTransfert(java.awt.event.ActionEvent evt) {
            this.finish = false;
            if (this.file != null) {
                this.label.setText("Transfert du fichier : "+this.file.getName()+" en cours...");
                this.thread = new ThreadUpload("upload", this);
                this.progress.setIndeterminate(false);
                this.btnOpen.setEnabled(false);
                this.btnOk.setEnabled(false);
                this.btnStop.setEnabled(true);
                this.thread.start();
            } else {
                this.label.setText("Veuillez sélectionner votre fichier.");
                this.btnOpen.setEnabled(true);
                this.btnOk.setEnabled(false);
                this.btnStop.setEnabled(false);
            }
        }
     
        private void openFile(java.awt.event.ActionEvent evt) {
            try {
                JFileChooser tmp = new JFileChooser();
                int i = tmp.showOpenDialog(this);
                if (i != tmp.CANCEL_OPTION) {
                    this.file = tmp.getSelectedFile();
                    this.lblSize.setText("Taille : " + sizeToString(0, 1) + " / " + sizeToString(((int)this.file.length()),3));
                    this.label.setText("Fichier : "+this.file.getName()+" sélectionné.");
                    this.btnOk.setEnabled(true);
                    this.btnStop.setEnabled(false);
                } else {
                    this.file = null;
                    this.btnOk.setEnabled(false);
                    this.btnStop.setEnabled(false);
                    this.label.setText("Veuillez sélectionner votre fichier.");
                }
            } catch (AccessControlException e) {
                this.label.setText("Vous devez accepter le certificat.");
                this.btnOk.setEnabled(false);
                this.btnOpen.setEnabled(false);
                this.btnStop.setEnabled(false);
            }
        }
     
        public boolean showDialog() {
            this.setVisible(true);
            return this.isok;
        }
     
        public void exit() {
            if (this.thread == null) {
                this.parent.reinitUpload();
                setVisible(false);
            } else if (this.finish) {
                this.parent.finaliseUpload(this.thread.getDestinationName());
                setVisible(false);
            }
        }
     
        public String getDestinationName () {
            return this.thread.getDestinationName();
        }
     
        public JProgressBar getProgressBar() {
            return this.progress;
        }
     
        public JLabel getLabel() {
            return this.label;
        }
     
        public File getFile() {
            return this.file;
        }
     
        public void finalizeUpload(boolean isok) {
            if (isok) {
                this.progress.setIndeterminate(false);
                this.progress.setValue(100);
                this.label.setText("Fichier : "+this.file.getName()+" transféré.");
                this.lblPercent.setText("100%");
                this.lblSize.setText("Taille : "+sizeToString(((int)this.file.length()),3)+"/"+sizeToString(((int)this.file.length()),3));
                this.isok = isok;
                this.finish = true;
                this.parent.setFile(this.file);
                this.btnStop.setEnabled(false);
                this.btnOpen.setEnabled(false);
                this.btnOk.setEnabled(false);
            } else {
                this.progress.setIndeterminate(false);
                this.progress.setValue(0);
                this.label.setText("Fichier : "+this.file.getName()+" non transféré.");
                this.isok = isok;
                this.finish = false;
                this.btnStop.setEnabled(false);
                this.btnOk.setEnabled(true);
                this.btnOpen.setEnabled(true);
                this.thread = null;
            }
        }
     
        public void setUncontrolTransfert() {
            this.progress.setIndeterminate(true);
        }
     
        public String sizeToString (int size, int limit) {
            String[] SIZES = {"o" , "Ko", "Mo", "Go", "To"};
            int size_id = 0;
            float sizer = size;
            while (sizer > 1000 && size_id <= limit) {
              sizer = ((float)sizer/1024);
              size_id ++;
            }
            String str_size = "" + sizer;
            int idx = str_size.indexOf('.');
            if (idx != -1 ? (idx+3 < str_size.length()) : false) {
                str_size = str_size.substring(0, idx+3);
            }
            return "" + str_size + " " + SIZES[size_id];
        }
     
        public void setStatus (int stat) {
          this.lblSize.setText("Taille : " + sizeToString(stat, 1) + " / " + sizeToString(((int)this.file.length()),3));
     
          float tempo = ((float)(((float)stat/((float)this.file.length())) * 100));
          int percent = ((int)tempo);
     
          this.lblPercent.setText( percent + "%");
          this.progress.setValue(percent);
        }
     
     
        private javax.swing.JButton btnOk;
        private javax.swing.JButton btnOpen;
        private javax.swing.JButton btnStop;
        private javax.swing.JLabel label;
        private javax.swing.JLabel lblPercent;
        private javax.swing.JLabel lblSize;
        private javax.swing.JPanel pnlCompteurs;
        private javax.swing.JPanel pnlHaut;
        private javax.swing.JPanel pnlTransfert;
        private javax.swing.JProgressBar progress;
     
     
    }
    Goah Sha Kree

  19. #59
    Membre actif
    Avatar de jak0
    Profil pro
    Inscrit en
    Mai 2005
    Messages
    272
    Détails du profil
    Informations personnelles :
    Localisation : France

    Informations forums :
    Inscription : Mai 2005
    Messages : 272
    Points : 219
    Points
    219
    Par défaut
    Fichier Uploader.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
    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
    import java.awt.BorderLayout;
    import java.awt.event.ActionEvent;
    import java.io.File;
    import javax.swing.JApplet;
    import javax.swing.JButton;
    import netscape.javascript.JSException;
    import netscape.javascript.JSObject;
     
    public class Uploader extends JApplet {
     
        private JButton uploadLauncher;
        private Transfert dialog;
        private File file;
        private String id;
     
     
        public Uploader() {
            super();
        }
        public String getElementById(String id) {
            try {
                JSObject wina;
                try {
                    wina = JSObject.getWindow(this);
                    return (String)wina.eval("javascript:document.getElementById('"+id+"').value;");
                } catch (JSException jse) {
                    System.out.println(" bug a revoir, solution temporaire apporte");
                    wina = JSObject.getWindow(this);
                }
                return (String)wina.eval("javascript:document.getElementById('"+id+"').value;");
            } catch (JSException e) { e.printStackTrace(); return ""; }
        }
     
        public void setElementById(String id,String value) {
            try {
                JSObject wina;
     
                try {
                    wina = JSObject.getWindow(this);
                } catch (JSException jse) {
                    System.out.println("bug a revoir, solution temporaire apporte");
                    wina = JSObject.getWindow(this);
                }
                wina.eval("javascript:document.getElementById('"+id+"').value = '"+value+"';");
            } catch (JSException e) { e.printStackTrace(); }
        }
     
        public static boolean parseJSToBoolean(String js) {
            return (js.equals("1") || "true".equals(js.toLowerCase()));
        }
     
      public static String parseBooleanToJS(boolean bool) {
            if (bool) {
                return "1";
            } else {
                return "0";
            }
        }
     
        public void init() {
            this.id = "id";
            this.uploadLauncher = new JButton("Transférer avec Java");
            this.getContentPane().setLayout(new BorderLayout());
            this.getContentPane().add(this.uploadLauncher);
            this.uploadLauncher.addActionListener(new java.awt.event.ActionListener() {
                public void actionPerformed(java.awt.event.ActionEvent evt) {
                    launchUpload(evt);
                }
            });
            if (this.id == null) {
                this.uploadLauncher.setEnabled(false);
            }
            setElementById(this.id+"-text", "en cours...");
            setElementById(this.id+"-real", "");
        }
     
        public String getFile() {
            try {
                return this.dialog.getDestinationName();
            } catch (NullPointerException e) {
                return null;
            }
        }
        public void setFile(File file) {
            this.file = file;
        }
     
        public void launchUpload(ActionEvent e) {
            this.dialog = new Transfert(this);
            this.dialog.showDialog();
            this.uploadLauncher.setEnabled(false);
        }
     
        public void reinitUpload() {
            this.dialog = null;
            this.uploadLauncher.setEnabled(true);
        }
     
        public void finaliseUpload(String destination_name) {
            System.out.println("Fin d'utilisation, récupération du fichier");
            setElementById(this.id+"-text", destination_name);
            setElementById(this.id+"-real", destination_name);
            System.out.println("on applique le fichier ("+destination_name+")à l'élément d'id : "+this.id+"-real");
     
        }
    }
    Goah Sha Kree

  20. #60
    Membre actif
    Avatar de jak0
    Profil pro
    Inscrit en
    Mai 2005
    Messages
    272
    Détails du profil
    Informations personnelles :
    Localisation : France

    Informations forums :
    Inscription : Mai 2005
    Messages : 272
    Points : 219
    Points
    219
    Par défaut
    Fichier FTPConnection.java (modifié) :
    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
    158
    159
    160
    161
    162
    163
    164
    165
    166
    167
    168
    169
    170
    171
    172
    173
    174
    175
    176
    177
    178
    179
    180
    181
    182
    183
    184
    185
    186
    187
    188
    189
    190
    191
    192
    193
    194
    195
    196
    197
    198
    199
    200
    201
    202
    203
    204
    205
    206
    207
    208
    209
    210
    211
    212
    213
    214
    215
    216
    217
    218
    219
    220
    221
    222
    223
    224
    225
    226
    227
    228
    229
    230
    231
    232
    233
    234
    235
    236
    237
    238
    239
    240
    241
    242
    243
    244
    245
    246
    247
    248
    249
    250
    251
    252
    253
    254
    255
    256
    257
    258
    259
    260
    261
    262
    263
    264
    265
    266
    267
    268
    269
    270
    271
    272
    273
    274
    275
    276
    277
    278
    279
    280
    281
    282
    283
    284
    285
    286
    287
    288
    289
    290
    291
    292
    293
    294
    295
    296
    297
    298
    299
    300
    301
    302
    303
    304
    305
    306
    307
    308
    309
    310
    311
    312
    313
    314
    315
    316
    317
    318
    319
    320
    321
    322
    323
    324
    325
    326
    327
    328
    329
    330
    331
    332
    333
    334
    335
    336
    337
    338
    339
    340
    341
    342
    343
    344
    345
    346
    347
    348
    349
    350
    351
    352
    353
    354
    355
    356
    357
    358
    359
    360
    361
    362
    363
    364
    365
    366
    367
    368
    369
    370
    371
    372
    373
    374
    375
    376
    377
    378
    379
    380
    381
    382
    383
    384
    385
    386
    387
    388
    389
    390
    391
    392
    393
    394
    395
    396
    397
    398
    399
    400
    401
    402
    403
    404
    405
    406
    407
    408
    409
    410
    411
    412
    413
    414
    415
    416
    417
    418
    419
    420
    421
    422
    423
    424
    425
    426
    427
    428
    429
    430
    431
    432
    433
    434
    435
    436
    437
    438
    439
    440
    441
    442
    443
    444
    445
    446
    447
    448
    449
    450
    451
    452
    453
    454
    455
    456
    457
    458
    459
    460
    461
    462
    463
    464
    465
    466
    467
    468
    469
    470
    471
    472
    473
    474
    475
    476
    477
    478
    479
    480
    481
    482
    483
    484
    485
    486
    487
    488
    489
    490
    491
    492
    493
    494
    495
    496
    497
    498
    499
    500
    501
    502
    503
    504
    505
    506
    507
    508
    509
    510
    511
    512
    513
    514
    515
    516
    517
    518
    519
    520
    521
    522
    523
    524
    525
    526
    527
    528
    529
    530
    531
    532
    533
    534
    535
    536
    537
    538
    539
    540
    541
    542
    543
    544
    545
    546
    547
    548
    549
    550
    551
    552
    553
    554
    555
    556
    557
    558
    559
    560
    561
    562
    563
    564
    565
    566
    567
    568
    569
    570
    571
    572
    573
    574
    575
    576
    577
    578
    579
    580
    581
    582
    583
    584
    585
    586
    587
    588
    589
    590
    591
    592
    593
    594
    595
    596
    597
    598
    599
    600
    601
    602
    603
    604
    605
    606
    607
    608
    609
    610
    611
    612
    613
    614
    615
    616
    617
    618
    import java.io.*;
    import java.net.*;
    import java.util.*;
     
    public class FTPConnection extends Object {
     
        private static boolean PRINT_DEBUG_INFO = false;
        private Socket connectionSocket = null;
        private PrintStream outputStream = null;
        private BufferedReader inputStream = null;
        private long restartPoint = 0L;
        private boolean loggedIn = false;
        public String lineTerm = "\n";
        private static int BLOCK_SIZE = 4096;
        private ThreadUpload uploader = null;
     
        public FTPConnection (ThreadUpload uploader)
        {
            this.uploader = uploader;
        }
     
     
        public FTPConnection (boolean debugOut)
        {
        	PRINT_DEBUG_INFO = debugOut;
        }
     
     
        private void debugPrint(String message) {
            if (PRINT_DEBUG_INFO) System.err.println(message);
        }
     
     
        public boolean connect(String host)
            throws UnknownHostException, IOException
        {
            return connect(host, 21);
        }
     
     
        public boolean connect(String host, int port)
            throws UnknownHostException, IOException
        {
            connectionSocket = new Socket(host, port);
            outputStream = new PrintStream(connectionSocket.getOutputStream());
            inputStream = new BufferedReader(new
                           InputStreamReader(connectionSocket.getInputStream()));
     
            if (!isPositiveCompleteResponse(getServerReply())){
                disconnect();
                return false;
            }
     
            return true;
        }
     
        public void forceDisconnect() {
            if (outputStream != null) {
                outputStream.close();
                outputStream = null;
            }
            disconnect();
        }
     
        public void disconnect()
        {
            if (outputStream != null) {
                try {
            		if (loggedIn) { logout(); };
                    outputStream.close();
                    inputStream.close();
                    connectionSocket.close();
                } catch (IOException e) {}
     
                outputStream = null;
                inputStream = null;
                connectionSocket = null;
            }
        }
     
     
        public boolean login(String username, String password)
            throws IOException
        {
            int response = executeCommand("user " + username);
            if (!isPositiveIntermediateResponse(response)) return false;
            response = executeCommand("pass " + password);
            loggedIn = isPositiveCompleteResponse(response);
            return loggedIn;
        }
     
     
        public boolean logout()
            throws IOException
        {
            int response = executeCommand("quit");
            loggedIn = !isPositiveCompleteResponse(response);
            return !loggedIn;
        }
     
     
        public boolean changeDirectory(String directory)
            throws IOException
        {
            int response = executeCommand("cwd " + directory);
            return isPositiveCompleteResponse(response);
        }
     
     
        public boolean renameFile(String oldName, String newName)
            throws IOException
        {
            int response = executeCommand("rnfr " + oldName);
            if (!isPositiveIntermediateResponse(response)) return false;
            response = executeCommand("rnto " + newName);
            return isPositiveCompleteResponse(response);
        }
     
     
        public boolean makeDirectory(String directory)
            throws IOException
        {
            int response = executeCommand("mkd " + directory);
            return isPositiveCompleteResponse(response);
        }
     
     
        public boolean removeDirectory(String directory)
            throws IOException
        {
            int response = executeCommand("rmd " + directory);
            return isPositiveCompleteResponse(response);
        }
     
     
        public boolean parentDirectory()
            throws IOException
        {
            int response = executeCommand("cdup");
            return isPositiveCompleteResponse(response);
        }
     
     
        public boolean deleteFile(String fileName)
            throws IOException
        {
            int response = executeCommand("dele " + fileName);
            return isPositiveCompleteResponse(response);
        }
     
     
        public String getCurrentDirectory()
            throws IOException
        {
            String response = getExecutionResponse("pwd");
            StringTokenizer strtok = new StringTokenizer(response);
     
            if (strtok.countTokens() < 2) return null;
            strtok.nextToken();
            String directoryName = strtok.nextToken();
     
            int strlen = directoryName.length();
            if (strlen == 0) return null;
            if (directoryName.charAt(0) == '\"') {
                directoryName = directoryName.substring(1);
                strlen--;
            }
            if (directoryName.charAt(strlen - 1) == '\"')
                return directoryName.substring(0, strlen - 1);
            return directoryName;
        }
     
     
        public String getSystemType()
            throws IOException
        {
            return excludeCode(getExecutionResponse("syst"));
        }
     
     
        public long getModificationTime(String fileName)
            throws IOException
        {
            String response = excludeCode(getExecutionResponse("mdtm " + fileName));
            try {
                return Long.parseLong(response);
            } catch (Exception e) {
                return -1L;
            }
        }
     
     
        public long getFileSize(String fileName)
            throws IOException
        {
            String response = excludeCode(getExecutionResponse("size " + fileName));
            try {
                return Long.parseLong(response);
            } catch (Exception e) {
                return -1L;
            }
        }
     
     
        public boolean downloadFile(String fileName)
            throws IOException
        {
            return readDataToFile("retr " + fileName, fileName);
        }
     
     
        public boolean downloadFile(String serverPath, String localPath)
            throws IOException
        {
            return readDataToFile("retr " + serverPath, localPath);
        }
     
     
        public boolean uploadFile(String fileName)
            throws IOException
        {
            return writeDataFromFile("stor "  + fileName, fileName);
        }
     
     
        public boolean uploadFile(String serverPath, String localPath)
            throws IOException
        {
            return writeDataFromFile("stor " + serverPath, localPath);
        }
     
     
        public void setRestartPoint(int point)
        {
            restartPoint = point;
            debugPrint("Restart noted");
        }
     
     
        private int getServerReply()
            throws IOException
        {
            return Integer.parseInt(getFullServerReply().substring(0, 3));
        }
     
     
        private String getFullServerReply()
            throws IOException
        {
            String reply;
     
            do {
                reply = inputStream.readLine();
                debugPrint(reply);
            } while(!(Character.isDigit(reply.charAt(0)) && 
                      Character.isDigit(reply.charAt(1)) &&
                      Character.isDigit(reply.charAt(2)) &&
                      reply.charAt(3) == ' '));
     
            return reply;
        }
     
     
        private String getFullServerReply(StringBuffer fullReply)
        	throws IOException
        {
            String reply;
            fullReply.setLength(0);
     
            do {
                reply = inputStream.readLine();
                debugPrint(reply);
                fullReply.append(reply + lineTerm);
            } while(!(Character.isDigit(reply.charAt(0)) && 
                      Character.isDigit(reply.charAt(1)) &&
                      Character.isDigit(reply.charAt(2)) &&
                      reply.charAt(3) == ' '));
     
    		if (fullReply.length() > 0)  
    		{  
    			fullReply.setLength(fullReply.length() - lineTerm.length());
    		}
     
            return reply;
        }
     
     
     
    	public String listFiles()
    		throws IOException
    	{
    		return listFiles("");
    	}
     
     
    	public String listFiles(String params)
    		throws IOException
    	{
    		StringBuffer files = new StringBuffer();
    		StringBuffer dirs = new StringBuffer();
    		if (!getAndParseDirList(params, files, dirs))
    		{
    			debugPrint("Error getting file list");
    		}
     
    		return files.toString();
    	}
     
     
    	public String listSubdirectories()
    		throws IOException
    	{
    		return listSubdirectories("");
    	}
     
     
    	public String listSubdirectories(String params)
    		throws IOException
    	{
    		StringBuffer files = new StringBuffer();
    		StringBuffer dirs = new StringBuffer();
    		if (!getAndParseDirList(params, files, dirs))
    		{
    			debugPrint("Error getting dir list");
    		}
     
    		return dirs.toString();
    	}
     
     
        private String processFileListCommand(String command)
            throws IOException
        {
            StringBuffer reply = new StringBuffer();
            String replyString;
     
    		boolean success = executeDataCommand(command, reply);
    		if (!success)
    		{
    			return "";
    		}
     
            replyString = reply.toString();
            if (reply.length() > 0)
            {
            	return replyString.substring(0, reply.length() - 1);
            }  else  {
            	return replyString;
            }
        }
     
     
    	private boolean getAndParseDirList(String params, StringBuffer files, StringBuffer dirs)
    		throws IOException
    	{
    		files.setLength(0);
    		dirs.setLength(0);
     
    		String shortList = processFileListCommand("nlst " + params);
    		String longList = processFileListCommand("list " + params);
     
    		StringTokenizer sList = new StringTokenizer(shortList, "\n");
    		StringTokenizer lList = new StringTokenizer(longList, "\n");
     
    		String sString;
    		String lString;
     
    		while ((sList.hasMoreTokens()) && (lList.hasMoreTokens())) {
    			sString = sList.nextToken();
    			lString = lList.nextToken();
    			if (lString.length() > 0)
    			{
    				if (lString.startsWith("d"))
    				{
    					dirs.append(lString.trim() + lineTerm);
    					debugPrint("Dir: " + sString);
    				}  else if (lString.startsWith("-"))  {
    					files.append(lString.trim() + lineTerm);
    					debugPrint("File: " + sString);
    				}  else  {
    					debugPrint("Unknown: " + lString);
    				}
    			}
    		}
     
    		if (files.length() > 0)  {  files.setLength(files.length() - lineTerm.length());  }
    		if (dirs.length() > 0)  {  dirs.setLength(dirs.length() - lineTerm.length());  }
     
    		return true;
    	}
     
     
        public int executeCommand(String command)
            throws IOException
        {
            outputStream.println(command);
            return getServerReply();
        }
     
     
        public String getExecutionResponse(String command)
            throws IOException
        {
            outputStream.println(command);
            return getFullServerReply();
        }
     
     
        public boolean readDataToFile(String command, String fileName)
            throws IOException
        {
            RandomAccessFile outfile = new RandomAccessFile(fileName, "rw");
     
            if (restartPoint != 0) {
                debugPrint("Seeking to " + restartPoint);
                outfile.seek(restartPoint);
            }
     
            FileOutputStream fileStream = new FileOutputStream(outfile.getFD());
            boolean success = executeDataCommand(command, fileStream);
     
            outfile.close();
     
            return success;
        }
     
     
        public boolean writeDataFromFile(String command, String fileName)
            throws IOException
        {
            RandomAccessFile infile = new RandomAccessFile(fileName, "r");
     
            if (restartPoint != 0) {
                debugPrint("Seeking to " + restartPoint);
                infile.seek(restartPoint);
            }
     
            FileInputStream fileStream = new FileInputStream(infile.getFD());
            boolean success = executeDataCommand(command, fileStream);
     
            infile.close();
     
            return success;
        }
     
     
        public boolean executeDataCommand(String command, OutputStream out)
            throws IOException
        {
            ServerSocket serverSocket = new ServerSocket(0);
            if (!setupDataPort(command, serverSocket)) return false;
            Socket clientSocket = serverSocket.accept();
     
            InputStream in = clientSocket.getInputStream();
            transferData(in, out);
     
            in.close();
            clientSocket.close();
            serverSocket.close();
     
            return isPositiveCompleteResponse(getServerReply());    
        }
     
     
        public boolean executeDataCommand(String command, InputStream in)
            throws IOException
        {
            ServerSocket serverSocket = new ServerSocket(0);
            if (!setupDataPort(command, serverSocket)) return false;
            Socket clientSocket = serverSocket.accept();
     
            OutputStream out = clientSocket.getOutputStream();
            transferData(in, out);
     
            out.close();
            clientSocket.close();
            serverSocket.close();
     
            return isPositiveCompleteResponse(getServerReply());    
        }
     
     
        public boolean executeDataCommand(String command, StringBuffer sb)
            throws IOException
        {
            ServerSocket serverSocket = new ServerSocket(0);
            if (!setupDataPort(command, serverSocket)) return false;
            Socket clientSocket = serverSocket.accept();
     
            InputStream in = clientSocket.getInputStream();
            transferData(in, sb);
     
            in.close();
            clientSocket.close();
            serverSocket.close();
     
            return isPositiveCompleteResponse(getServerReply());    
        }
     
     
        private void transferData(InputStream in, OutputStream out)
            throws IOException
        {
            byte b[] = new byte[BLOCK_SIZE];
            int amount;
     
            while ((amount = in.read(b)) > 0) {
                out.write(b, 0, amount);
                this.uploader.setStatus(amount);
            }
            this.uploader.finalizeUpload(true);
        }
     
     
        private void transferData(InputStream in, StringBuffer sb)
            throws IOException
        {
            byte b[] = new byte[BLOCK_SIZE];
            int amount;
     
            while ((amount = in.read(b)) > 0) {
                sb.append(new String(b, 0, amount));
            }
        }
     
     
        private boolean setupDataPort(String command, ServerSocket serverSocket)
            throws IOException
        {
            if (!openPort(serverSocket)) return false;
     
            outputStream.println("type i");
            if (!isPositiveCompleteResponse(getServerReply())) {
                debugPrint("Could not set transfer type");
                return false;
            }
     
            if (restartPoint != 0) {
                outputStream.println("rest " + restartPoint);
                restartPoint = 0;
                getServerReply();
            }
     
            outputStream.println(command);
     
            return isPositivePreliminaryResponse(getServerReply());
        }
     
     
        private boolean openPort(ServerSocket serverSocket)
            throws IOException
        {                        
            int localport = serverSocket.getLocalPort();
     
            InetAddress inetaddress = serverSocket.getInetAddress();
            InetAddress localip;
            try {
                localip = inetaddress.getLocalHost();
            } catch(UnknownHostException e) {
                debugPrint("Can't get local host");
                return false;
            }
     
            byte[] addrbytes = localip.getAddress();
     
            short addrshorts[] = new short[4];
     
            for(int i = 0; i <= 3; i++) {
                addrshorts[i] = addrbytes[i];
                if (addrshorts[i] < 0)
                    addrshorts[i] += 256;
            }
     
            outputStream.println("port " + addrshorts[0] + "," + addrshorts[1] +
                                 "," + addrshorts[2] + "," + addrshorts[3] + "," +
                                 ((localport & 0xff00) >> 8) + "," +
                                 (localport & 0x00ff));
     
            return isPositiveCompleteResponse(getServerReply());
        }
     
     
        private boolean isPositivePreliminaryResponse(int response)
        {
            return (response >= 100 && response < 200);
        }
     
     
        private boolean isPositiveIntermediateResponse(int response)
        {
            return (response >= 300 && response < 400);
        }
     
        private boolean isPositiveCompleteResponse(int response)
        {
            return (response >= 200 && response < 300);
        }
     
     
        private boolean isTransientNegativeResponse(int response)
        {
            return (response >= 400 && response < 500);
        }
     
     
        private boolean isPermanentNegativeResponse(int response)
        {
            return (response >= 500 && response < 600);
        }
     
     
        private String excludeCode(String response)
        {
            if (response.length() < 5) return response;
            return response.substring(4);
        }
     
    }
    Goah Sha Kree

Discussions similaires

  1. Upload de fichiers sur FTP
    Par Copernic09 dans le forum VBA Access
    Réponses: 14
    Dernier message: 26/08/2009, 21h15
  2. uploader un fichier sur ftp
    Par kohsaka dans le forum VB.NET
    Réponses: 3
    Dernier message: 26/02/2008, 15h05
  3. [Upload] Upload de fichier sur intranet
    Par xaaros dans le forum Langage
    Réponses: 2
    Dernier message: 15/12/2006, 08h53
  4. Réponses: 3
    Dernier message: 20/04/2006, 23h21
  5. [Upload] upload de fichier par ftp
    Par sami_c dans le forum Langage
    Réponses: 3
    Dernier message: 22/03/2006, 11h18

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