|
|
|
|
Salut
as tu bien fait ta declaration au debut progress m_bar; dans ton code ensuite as tu aussi mis en debut de chaque classe package chemin.nom_package; et oui vive le Québec libre qu'ont en finissent une bonne fois pour toute avec tous ces chanteurs quebequois ;-)( je lol) |
Lol! Si tout le monde pensait comme toi, ça ferait longtemps que le Québec serait indépendant!
Pour revenir au problème, j'ai bien fait ce que tu as dit. J'ai réussi à faire les .class (enfin) avec la commande javac javaupload/*.java. Je ne réussi pas à les faire séparément mais si je fais cette commande, ça me créer les fichiers. J'ai cependant un autre problème: Je veux afficher cet applet dans ma page web. La page est située dans le même dossier que les .class. Mais j'obtiens cette erreur dans la console java: java.lang.NoClassDefFoundError: upload (wrong name: javaupload/upload) Le code de ma page web est : <HTML> <HEAD> <TITLE>Upload</TITLE> </HEAD> <BODY> <APPLET Code="upload.class" Width=300 Height=50> Votre navigateur ne supporte pas les applets. </APPLET> </BODY> </HTML> Est-ce que je dois mettre le nom de tous mes fichiers .class? Si oui, où dois-je le faire? Pourquoi ça donne cette erreur? Vive le Québec libre! Et oui, je suis québécoise... |
pour les faire separement t as essayé
java maclasse.java tout simplement? Sinon pour l appel ya pas de prob si tout est bien dans le meme repertoir... (upload fait apple au 3 clss restante?) |
J'ai essayé javac maclasse.java mais pas java maclasse.java.
Je suis capable de créer seulement un des fichiers avec ca, les trois autres ca ne marche pas. La seule façon c'est de les faire tous à la fois. Upload fait appel à une des autres classes. T'as une idée de pouquoi ca marche pas? Vive le Québec libre! Et oui, je suis québécoise... |
oups pardon c est bien javac lol j ai rippé...
tu as essayé en utilisant un cmpilateur style jcreator..pour compiler le tout dans le package proprement il te donnera peu etre plus de detail...tu devrai trouver des version shareware sur le net... bon courage.. |
J'ai essayé avec JBuilder mais ça ne fonctionne pas. Il dit qu'il ne trouve pas le main... c'est sûr c'est un applet! Alors je ne peux pas faire mes fichiers .class avec JBuilder. C'est pour ça que je les ai fait manuellement avec le terminal.
Je me suis fait un autre applet plus simple pour tester, mais ça ne marche pas plus. Vive le Québec libre! Et oui, je suis québécoise... |
tu pourrai me copier coller le code de l applet ici histoire de voir ce qui pourrai bloquer. |
Voici le code de des fichiers (je l'ai pris sur internet)
// Fichier PROGRESS.JAVA package javaupload; import javaupload.*; import java.awt.Canvas; import java.awt.Graphics; public class progress extends Canvas { public float percent = 0; public int bar_width = 0; public int bar_height = 0; public progress() { setSize(200, 25); } public void doresize(int width,int height) { bar_width = width; bar_height = height; // setSize(width,25); } public void paint(Graphics g) { int width = 0; if (percent != 0) { int thebar_width = bar_width - 10; if (thebar_width < 1) { thebar_width = 1; } width = (int) ((float) thebar_width * (float) percent / (float) 100); g.fill3DRect(0, 0, width, 24, true); // draw border } else { g.fill3DRect(0, 0, 1, 24,true); // draw border } // g.drawString(percent+" %", 1,20); } } // FICHIER UPLOAD.JAVA package javaupload; import javaupload.*; import java.applet.Applet; import java.awt.*; import java.awt.event.*; import java.awt.Button; import java.util.*; import java.lang.Integer; import java.lang.String; import java.net.*; public class upload extends Applet implements ActionListener { public void init() { //Button uploadButton = new Button(getParameter("jupload_button_text")); Button uploadButton = new Button("Test"); add(uploadButton); uploadButton.addActionListener(this); } public void actionPerformed(ActionEvent event) { /*uploadThread upTh = new uploadThread(getParameter("jupload_up_url"), getParameter("jupload_file_varname"));*/ //upTh.start(); } } //FICHIER UPLOADTHREAD.JAVA package javaupload; import javaupload.*; import java.net.*; import java.io.*; import java.util.*; import java.lang.Integer; import java.lang.String; public class uploadThread extends Thread { String m_myUrl = ""; String m_filenameVarName = ""; public uploadThread (String uploadUrl, String filenameVarName) { m_myUrl = uploadUrl; m_filenameVarName = filenameVarName; } public void run() { uploadWindow w = new uploadWindow (m_filenameVarName, m_myUrl); } } //ET FINALEMENT FICHIER UPLOADWINDOW.JAVA package javaupload; import javaupload.*; import java.applet.Applet; import java.awt.*; import java.awt.event.*; import java.awt.Button; import java.util.*; import java.lang.Integer; import java.lang.String; import java.net.*; import java.io.*; //import java.io.stream.*; //import com.ms.security.*; public class uploadWindow implements ActionListener,WindowListener{ Frame m_frame; Thread m_thread; // Applet parameters goes here // May depend on your upload speed and machine power. On my 700 MHz, with a 100 Mbit link, // a value less than 10 KB slows down upload. With 2 KB, max upload speed was 2000 MB/s. // A value higher than 2 KB/packet means that it may not display fast enought on RTC modems/links. int uploadPacketSize = 8*1024; // AWT variables Panel m_top = new Panel(new BorderLayout()); Panel m_center = new Panel(new BorderLayout()); Panel m_bottom = new Panel(new FlowLayout()); String m_title; Label m_rateLabel; Label m_status; Button m_cancelButton; Rectangle progressRect; progress m_bar; // The URL splited afet getURL() String noProtocolURL; // The url without protocols (like user:pass@www.example.com/uploadpath/uploadscript?myparam1=myvalue1) String serverNameUrl = "test"; // The server name (like www.example.com) String user="none"; // The user name String pass="none"; // The user pass int serverPort; // The server port String fileUploadPath; // The complete URL (like /uploadpath/uploadscript?myparam1=myvalue1&myparam2=myvalue2) String scriptPath; // The URL without parameters ( like /uploadpath/uploadscript) String scriptParameters; // The URL parameters (like myparam1=myvalue1&myparam2=myvalue2) int nbr_script_param; String[] toSendVarNames = new String[32]; String[] toSendVarValues = new String[32]; // Upload variables boolean ftp = false; boolean http = false; boolean usingPassword = false; InetAddress addr; Socket socket; BufferedOutputStream wr; // Temp variables Integer tempServerPort; public void myError(String message) { System.out.println(message); } // Avoid flickering but does not redraw canvas ! // public void update(Graphics g){paint(g;)} // Parse the input URL to separate server name, port, user, pass and destination file path public void getURL(String uploadPath) { // Get the connection methode (ftp or http) and remove it from the server URL if (uploadPath.startsWith("ftp://")) { ftp = true; noProtocolURL = uploadPath.substring(6); }else if (uploadPath.startsWith("http://")) { http = true; noProtocolURL = uploadPath.substring(7); }else{ // Todo : display an error message ! myError("Could not find a protocol prefix in the upload url !"); } // Find the user:pass@www.xyz.ab in a string of the type user:host@www.xyz.ab/end/of/the/url int serverNameLenght = noProtocolURL.indexOf('/'); if (serverNameLenght == -1) { myError("Could not find the first \"/\" after server name in the upload url !"); } serverNameUrl = noProtocolURL.substring(0,serverNameLenght); fileUploadPath = noProtocolURL.substring(serverNameLenght); // Verify there is no user:pass in server name int serverUserPassLenght = noProtocolURL.indexOf('@'); if (serverUserPassLenght != -1) { int usernameLenght; String userPass; usingPassword = true; userPass = serverNameUrl.substring(0,serverUserPassLenght); serverNameUrl = serverNameUrl.substring(serverUserPassLenght + 1, serverNameUrl.length()); // Retrive the username usernameLenght = userPass.indexOf(':'); if (usernameLenght == -1) { myError("There is an '@' sign in the URL, but no ':' for separating user and password !"); } user = userPass.substring(0, usernameLenght); pass = userPass.substring(usernameLenght + 1, userPass.length()); } // Retrive the port to connect to, and set default 21 or 80 if no port specified int serverNameWithoutPortLenght = serverNameUrl.indexOf(':'); if (serverUserPassLenght != -1) { String portString; portString = serverNameUrl.substring(serverNameWithoutPortLenght+1,serverNameUrl.length()); serverNameUrl = serverNameUrl.substring(0,serverNameWithoutPortLenght); serverPort = tempServerPort.parseInt(portString, 10); } else { if(http == true){ serverPort = 80; } else { serverPort = 21; } } // Separate the scripts parameters int scriptPathLength = fileUploadPath.indexOf('?'); nbr_script_param = 0; if (scriptPathLength != -1) { boolean parsingFinished=false; int endOfParamName; int nextParamIndex; String paramName; String paramValue; // System.out.println("Parameter detected !"); scriptPath = fileUploadPath.substring(0,scriptPathLength); scriptParameters = fileUploadPath.substring(scriptPathLength + 1, fileUploadPath.length()); // System.out.println("Script params are "+scriptParameters+" !"); while (parsingFinished == false) { // System.out.println("Parsing parameter "+nbr_script_param+" !"); endOfParamName = scriptParameters.indexOf('='); if (endOfParamName == -1) { System.out.println("Parsing error !"); return; } paramName = scriptParameters.substring(0, endOfParamName); paramValue = scriptParameters.substring(endOfParamName + 1, scriptParameters.length()); if ((nextParamIndex = paramValue.indexOf('&')) != -1) { scriptParameters = paramValue.substring(nextParamIndex + 1, paramValue.length()); paramValue = paramValue.substring(0, nextParamIndex); }else{ parsingFinished = true; } // System.out.println("Parameter "+nbr_script_param+" detected name : "+paramName); // System.out.println("Parameter "+nbr_script_param+" detected value : "+paramValue); toSendVarNames[nbr_script_param] = paramName; toSendVarValues[nbr_script_param] = paramValue; nbr_script_param += 1; } }else{ scriptPath = fileUploadPath; scriptParameters = ""; } } public uploadWindow (String filenameVarName, String uploadPath) { getURL (uploadPath); // CREATE THE WINDOW INTERFACE // Create the frame (called frame but is a detached window); m_title = "Transfert"; m_frame = new Frame(m_title); m_frame.setLayout(new BorderLayout()); m_frame.add(m_top, BorderLayout.NORTH); m_frame.add(m_center, BorderLayout.CENTER); m_frame.add(m_bottom, BorderLayout.SOUTH); // Add all the cancel button m_cancelButton = new Button("Cancel"); m_bottom.add(m_cancelButton, BorderLayout.CENTER); m_cancelButton.addActionListener(this); // Add the status label to it m_status = new Label("Initialisation..."); m_top.add(m_status, BorderLayout.WEST); // Add the transfer rate string m_rateLabel = new Label("Transfert : 0 Bps, 0%, 0 / 0 bytes, ETA: unknown"); m_top.add(m_rateLabel,BorderLayout.EAST); // Add a text field to draw debug messages // debugArea = new TextArea("Debug window",10,30); // m_center.add(debugArea); // debugArea.invalidate(); m_bar = new progress(); m_center.add(m_bar); // Get the progress indicator bounds progressRect = m_center.getBounds(); // Show the frame int width = 640; int height = 110; m_frame.setSize(width, height); m_frame.setVisible(true); m_frame.addWindowListener(this); m_thread = Thread.currentThread(); // Open the local file using file selector /* Popup file dialog (Fileselector) for choosing file to upload (needs FILE access in java security flags)*/ FileDialog fd = new FileDialog(m_frame, "Choisissez un fichier."); fd.setVisible(true); // Added getDirectory() so it can upload from anywhere String selectedFileName = fd.getDirectory() + fd.getFile(); if(selectedFileName == null){ m_frame.setVisible(false); return; } fd.dispose(); // Loads the file in memory for uploading File binaryFile = new File(selectedFileName); long binaryFileLength = binaryFile.length(); // Connect the socket to the selected ip and port m_status.setText("Recherche de l'hôte " + serverNameUrl + " ...") ; m_status.invalidate(); // Try resolving the server name (needs NET access in java security flags) try{ addr = InetAddress.getByName(serverNameUrl); }catch(Exception e){ m_status.setText("Erreur : hôte non trouvé !!!") ; m_status.invalidate(); return; } // Connect the socket // serverPort = 8003; m_status.setText("Connection à " + serverNameUrl + " sur le port " + serverPort + "...") ; m_status.repaint(); try { socket = new Socket(addr, serverPort); } catch(Exception e){ m_status.setText("Erreur : impossible de se connecter au site !!!") ; m_status.invalidate(); return; } m_status.setText("Connecté, création de la sortie : " + fileUploadPath + " Nombre de paramètres :" + nbr_script_param) ; m_status.invalidate(); try { wr = new BufferedOutputStream(socket.getOutputStream()); // uploadPacketSize = socket.getSendBufferSize(); // > java 1.1 ??? Does not seems to work everywhere... } catch (Exception e) { m_status.setText("Erreur : impossible de créer la sortie : " + uploadPath + " !"); m_status.invalidate(); return; } // Prepare what we will send (by constructing the HTTP header) // long contentLenght; String fileHeader ="-----------------------------7d2c0141d01c8\r\n"+ "Content-Disposition: form-data; name=\""+filenameVarName+"\"; filename=\""+selectedFileName+"\"\r\n"+ "Content-type: application/octet-stream\r\n\r\n"; String fileFooter ="\r\n-----------------------------7d2c0141d01c8--\r\n"; int j; String paramName; String paramValue; String encodedParams=""; for(j=0;j<nbr_script_param;j++){ paramName = toSendVarNames[j]; paramValue = toSendVarValues[j]; encodedParams += "-----------------------------7d2c0141d01c8\r\n"+ "Content-Disposition: form-data; name=\""+paramName+"\"\r\n\r\n"+paramValue+"\r\n"; } contentLenght = fileHeader.length() + encodedParams.length() + binaryFileLength + fileFooter.length(); String headerHTTP = ""; headerHTTP += "POST "+scriptPath+" HTTP/1.1\r\n"; headerHTTP += "Accept: image/gif, image/x-xbitmap, image/jpeg, image/pjpeg, application/vnd.ms-powerpoint, application/vnd.ms-excel, application/msword, */*\r\n"; headerHTTP += "Accept-Language: fr,en-us;q=0.7,zh;q=0.3\r\n"; headerHTTP += "Content-Type: multipart/form-data; boundary=---------------------------7d2c0141d01c8\r\n"; headerHTTP += "Accept-Encoding: gzip, deflate\r\n"; headerHTTP += "User-Agent: Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.0; .NET CLR 1.0.3705)\r\n"; headerHTTP += "Host: "+serverNameUrl+":"+serverPort+"\r\n"; // Content length does not include the CR LF headerHTTP += "Content-length: "+(contentLenght-2)+"\r\n"; headerHTTP += "Connection: Close\r\n"; headerHTTP += "Cache-Control: no-cache\r\n\r\n"+encodedParams; // Send the header m_status.setText("Envoi de l'en-tête HTTP..."); m_status.invalidate(); // My upload statistics Date startUploadDate = new Date(); Date curentDate=new Date(); long startMiliSec=startUploadDate.getTime(); long curentMiliSec=curentDate.getTime(); long timeEnlapsed=0; long transferRate=0; long remainingToSend; long eta=0; // Send the HTTP header byte[] plop; int len; plop = headerHTTP.getBytes(); len = headerHTTP.length(); try { wr.write(plop,0,len); } catch (Exception e) { m_status.setText("Erreur : impossible d'envoyer l'en-tête HTTP !") ; m_status.invalidate(); return; } // Send what I call the "file header" plop = fileHeader.getBytes(); len = fileHeader.length(); try { wr.write(plop,0,len); // wr.flush(); } catch (Exception e) { m_status.setText("Erreur : impossible d'envoyer l'en-tête de fichier !") ; m_status.invalidate(); return; } m_status.setText("Envoi des données à " + serverNameUrl + "..."); m_status.invalidate(); m_rateLabel.setText("Transfert : 0 Bps, 0 / " + binaryFileLength + " bytes, ETA: unknown"); m_rateLabel.invalidate(); // Send the file by packets of uploadPacketSize KB long i; int nbrLoop = (int)(binaryFileLength/uploadPacketSize); int lastPacketSize = (int)(binaryFileLength%uploadPacketSize); FileInputStream binaryFileStream; try { binaryFileStream= new FileInputStream(binaryFile); } catch (Exception e) { m_status.setText("Erreur durant la lecture du fichier !") ; m_status.invalidate(); return; } long byteTransfered = 0; byte[] buffer = new byte[uploadPacketSize]; for(i = 0; i < nbrLoop; i++){ try { binaryFileStream.read(buffer,0,uploadPacketSize); wr.write(buffer,0,uploadPacketSize); // wr.flush(); } catch (Exception e) { m_status.setText("Erreur durant l'upload !") ; m_status.invalidate(); return; } byteTransfered += uploadPacketSize; m_bar.percent = ( (byteTransfered*100) / binaryFileLength); if (m_bar.percent > 100) { m_bar.percent = 100; } int frame_width=m_frame.getSize().width; int frame_height=m_frame.getSize().height; if ((frame_width!=m_bar.bar_width) || (frame_height!=m_bar.bar_height)) { m_bar.doresize(frame_width,frame_height); } curentDate = new Date(); curentMiliSec=curentDate.getTime(); timeEnlapsed = curentMiliSec - startMiliSec; if(timeEnlapsed != 0 && byteTransfered != 0){ transferRate = (long)(((byteTransfered * 1000) / timeEnlapsed)/1024); remainingToSend = binaryFileLength - byteTransfered; eta = (long)(remainingToSend / (((byteTransfered * 1000) / timeEnlapsed))); } m_rateLabel.setText("Transfert : " + transferRate + " KBps, " + m_bar.percent+"%, " + byteTransfered + " / " + binaryFileLength+" bytes, ETA: "+eta+" s"); m_top.doLayout(); m_rateLabel.invalidate(); m_bar.invalidate(); m_bar.repaint(); m_center.repaint(); /* try{ Thread.sleep(20); // Helps debugging on very fast links }catch(Exception ex){ }*/ } // Send the last packet if exists if (lastPacketSize != 0) { try { binaryFileStream.read(buffer,0,lastPacketSize); wr.write(buffer,0,lastPacketSize); // wr.flush(); } catch (Exception e) { m_status.setText("Erreur durant la transmission du dernier paquet !") ; m_status.invalidate(); return; } byteTransfered+=lastPacketSize; m_bar.percent = 100; curentDate = new Date(); curentMiliSec = curentDate.getTime(); timeEnlapsed = curentMiliSec - startMiliSec; if (timeEnlapsed != 0) { transferRate = (long)(((byteTransfered * 1000) / timeEnlapsed)/1024); remainingToSend = binaryFileLength - byteTransfered; eta = (long)(remainingToSend / (((byteTransfered * 1000) / timeEnlapsed))); } m_rateLabel.setText("Transfert : " + transferRate+" KB/s, " + byteTransfered+" / " + binaryFileLength + " bytes, ETA: 0"); m_top.doLayout(); m_rateLabel.invalidate(); } // Send the "end of file boundary" m_status.setText("Envoi du pied de page HTTP..."); m_status.invalidate(); plop = fileFooter.getBytes(); len = fileFooter.length(); try { wr.write(plop,0,len); wr.flush(); m_rateLabel.setText("Fin du transfert à " + transferRate + " KB/s, " + binaryFileLength + " bytes in " + (long)(timeEnlapsed/1000) + " secondes"); m_top.doLayout(); m_rateLabel.invalidate(); m_status.setText("Fermeture de la connection..."); m_status.invalidate(); wr.close(); } catch(Exception e) { m_status.setText("Erreur à la fin de l'upload !") ; m_status.invalidate(); return; } // Todo : get and check the HTTP result to KNOW upload was successfull /* int byteRead=0; int ret; InputStreamReader inStream; byte[] anwserBuffer = new byte[uploadPacketSize]; try{ inStream = new InputStreamReader(socket.getInputStream()); }catch(Exception e){ m_status.setText("Error : could get socket read stream !!!"); m_status.invalidate(); return; } String test; try{ while((ret = inStream.read(anwserBuffer,0,512)) != -1){ byteRead+=ret; } }catch(Exception e){ m_status.setText("Error : could not read web server anwser !!!"); m_status.invalidate(); return; }*/ // Close the socket try { socket.close(); } catch(Exception e) { m_status.setText("Erreur : problème de fermeture de la connexion !!!"); m_status.invalidate(); return; } // Display the nice well done message and replace the "Cancel" by a "OK" button m_status.setText("Upload réussi !"); m_top.doLayout(); m_status.repaint(); m_cancelButton.setLabel("OK"); m_cancelButton.repaint(); } public void windowClosing (WindowEvent e) { m_frame.setVisible(false); m_thread.interrupt(); // destroy(); try { socket.close(); } catch(Exception ex){} } public void windowClosed(WindowEvent e) {} public void windowDeactivated(WindowEvent e) {} public void windowActivated(WindowEvent e) {} public void windowDeiconified(WindowEvent e) {} public void windowIconified(WindowEvent e) {} public void windowOpened(WindowEvent e) {} public void actionPerformed (ActionEvent e) { m_frame.setVisible(false); m_thread.interrupt(); // destroy(); try{ socket.close(); } catch(Exception ex) {} } } Vive le Québec libre! Et oui, je suis québécoise...Voici le code de des fichiers (je l'ai pris sur internet) // Fichier PROGRESS.JAVA package javaupload; import javaupload.*; import java.awt.Canvas; import java.awt.Graphics; public class progress extends Canvas { public float percent = 0; public int bar_width = 0; public int bar_height = 0; public progress() { setSize(200, 25); } public void doresize(int width,int height) { bar_width = width; bar_height = height; // setSize(width,25); } public void paint(Graphics g) { int width = 0; if (percent != 0) { int thebar_width = bar_width - 10; if (thebar_width < 1) { thebar_width = 1; } width = (int) ((float) thebar_width * (float) percent / (float) 100); g.fill3DRect(0, 0, width, 24, true); // draw border } else { g.fill3DRect(0, 0, 1, 24,true); // draw border } // g.drawString(percent+" %", 1,20); } } // FICHIER UPLOAD.JAVA package javaupload; import javaupload.*; import java.applet.Applet; import java.awt.*; import java.awt.event.*; import java.awt.Button; import java.util.*; import java.lang.Integer; import java.lang.String; import java.net.*; public class upload extends Applet implements ActionListener { public void init() { //Button uploadButton = new Button(getParameter("jupload_button_text")); Button uploadButton = new Button("Test"); add(uploadButton); uploadButton.addActionListener(this); } public void actionPerformed(ActionEvent event) { /*uploadThread upTh = new uploadThread(getParameter("jupload_up_url"), getParameter("jupload_file_varname"));*/ //upTh.start(); } } //FICHIER UPLOADTHREAD.JAVA package javaupload; import javaupload.*; import java.net.*; import java.io.*; import java.util.*; import java.lang.Integer; import java.lang.String; public class uploadThread extends Thread { String m_myUrl = ""; String m_filenameVarName = ""; public uploadThread (String uploadUrl, String filenameVarName) { m_myUrl = uploadUrl; m_filenameVarName = filenameVarName; } public void run() { uploadWindow w = new uploadWindow (m_filenameVarName, m_myUrl); } } //ET FINALEMENT FICHIER UPLOADWINDOW.JAVA package javaupload; import javaupload.*; import java.applet.Applet; import java.awt.*; import java.awt.event.*; import java.awt.Button; import java.util.*; import java.lang.Integer; import java.lang.String; import java.net.*; import java.io.*; //import java.io.stream.*; //import com.ms.security.*; public class uploadWindow implements ActionListener,WindowListener{ Frame m_frame; Thread m_thread; // Applet parameters goes here // May depend on your upload speed and machine power. On my 700 MHz, with a 100 Mbit link, // a value less than 10 KB slows down upload. With 2 KB, max upload speed was 2000 MB/s. // A value higher than 2 KB/packet means that it may not display fast enought on RTC modems/links. int uploadPacketSize = 8*1024; // AWT variables Panel m_top = new Panel(new BorderLayout()); Panel m_center = new Panel(new BorderLayout()); Panel m_bottom = new Panel(new FlowLayout()); String m_title; Label m_rateLabel; Label m_status; Button m_cancelButton; Rectangle progressRect; progress m_bar; // The URL splited afet getURL() String noProtocolURL; // The url without protocols (like user:pass@www.example.com/uploadpath/uploadscript?myparam1=myvalue1) String serverNameUrl = "test"; // The server name (like www.example.com) String user="none"; // The user name String pass="none"; // The user pass int serverPort; // The server port String fileUploadPath; // The complete URL (like /uploadpath/uploadscript?myparam1=myvalue1&myparam2=myvalue2) String scriptPath; // The URL without parameters ( like /uploadpath/uploadscript) String scriptParameters; // The URL parameters (like myparam1=myvalue1&myparam2=myvalue2) int nbr_script_param; String[] toSendVarNames = new String[32]; String[] toSendVarValues = new String[32]; // Upload variables boolean ftp = false; boolean http = false; boolean usingPassword = false; InetAddress addr; Socket socket; BufferedOutputStream wr; // Temp variables Integer tempServerPort; public void myError(String message) { System.out.println(message); } // Avoid flickering but does not redraw canvas ! // public void update(Graphics g){paint(g;)} // Parse the input URL to separate server name, port, user, pass and destination file path public void getURL(String uploadPath) { // Get the connection methode (ftp or http) and remove it from the server URL if (uploadPath.startsWith("ftp://")) { ftp = true; noProtocolURL = uploadPath.substring(6); }else if (uploadPath.startsWith("http://")) { http = true; noProtocolURL = uploadPath.substring(7); }else{ // Todo : display an error message ! myError("Could not find a protocol prefix in the upload url !"); } // Find the user:pass@www.xyz.ab in a string of the type user:host@www.xyz.ab/end/of/the/url int serverNameLenght = noProtocolURL.indexOf('/'); if (serverNameLenght == -1) { myError("Could not find the first \"/\" after server name in the upload url !"); } serverNameUrl = noProtocolURL.substring(0,serverNameLenght); fileUploadPath = noProtocolURL.substring(serverNameLenght); // Verify there is no user:pass in server name int serverUserPassLenght = noProtocolURL.indexOf('@'); if (serverUserPassLenght != -1) { int usernameLenght; String userPass; usingPassword = true; userPass = serverNameUrl.substring(0,serverUserPassLenght); serverNameUrl = serverNameUrl.substring(serverUserPassLenght + 1, serverNameUrl.length()); // Retrive the username usernameLenght = userPass.indexOf(':'); if (usernameLenght == -1) { myError("There is an '@' sign in the URL, but no ':' for separating user and password !"); } user = userPass.substring(0, usernameLenght); pass = userPass.substring(usernameLenght + 1, userPass.length()); } // Retrive the port to connect to, and set default 21 or 80 if no port specified int serverNameWithoutPortLenght = serverNameUrl.indexOf(':'); if (serverUserPassLenght != -1) { String portString; portString = serverNameUrl.substring(serverNameWithoutPortLenght+1,serverNameUrl.length()); serverNameUrl = serverNameUrl.substring(0,serverNameWithoutPortLenght); serverPort = tempServerPort.parseInt(portString, 10); } else { if(http == true){ serverPort = 80; } else { serverPort = 21; } } // Separate the scripts parameters int scriptPathLength = fileUploadPath.indexOf('?'); nbr_script_param = 0; if (scriptPathLength != -1) { boolean parsingFinished=false; int endOfParamName; int nextParamIndex; String paramName; String paramValue; // System.out.println("Parameter detected !"); scriptPath = fileUploadPath.substring(0,scriptPathLength); scriptParameters = fileUploadPath.substring(scriptPathLength + 1, fileUploadPath.length()); // System.out.println("Script params are "+scriptParameters+" !"); while (parsingFinished == false) { // System.out.println("Parsing parameter "+nbr_script_param+" !"); endOfParamName = scriptParameters.indexOf('='); if (endOfParamName == -1) { System.out.println("Parsing error !"); return; } paramName = scriptParameters.substring(0, endOfParamName); paramValue = scriptParameters.substring(endOfParamName + 1, scriptParameters.length()); if ((nextParamIndex = paramValue.indexOf('&')) != -1) { scriptParameters = paramValue.substring(nextParamIndex + 1, paramValue.length()); paramValue = paramValue.substring(0, nextParamIndex); }else{ parsingFinished = true; } // System.out.println("Parameter "+nbr_script_param+" detected name : "+paramName); // System.out.println("Parameter "+nbr_script_param+" detected value : "+paramValue); toSendVarNames[nbr_script_param] = paramName; toSendVarValues[nbr_script_param] = paramValue; nbr_script_param += 1; } }else{ scriptPath = fileUploadPath; scriptParameters = ""; } } public uploadWindow (String filenameVarName, String uploadPath) { getURL (uploadPath); // CREATE THE WINDOW INTERFACE // Create the frame (called frame but is a detached window); m_title = "Transfert"; m_frame = new Frame(m_title); m_frame.setLayout(new BorderLayout()); m_frame.add(m_top, BorderLayout.NORTH); m_frame.add(m_center, BorderLayout.CENTER); m_frame.add(m_bottom, BorderLayout.SOUTH); // Add all the cancel button m_cancelButton = new Button("Cancel"); m_bottom.add(m_cancelButton, BorderLayout.CENTER); m_cancelButton.addActionListener(this); // Add the status label to it m_status = new Label("Initialisation..."); m_top.add(m_status, BorderLayout.WEST); // Add the transfer rate string m_rateLabel = new Label("Transfert : 0 Bps, 0%, 0 / 0 bytes, ETA: unknown"); m_top.add(m_rateLabel,BorderLayout.EAST); // Add a text field to draw debug messages // debugArea = new TextArea("Debug window",10,30); // m_center.add(debugArea); // debugArea.invalidate(); m_bar = new progress(); m_center.add(m_bar); // Get the progress indicator bounds progressRect = m_center.getBounds(); // Show the frame int width = 640; int height = 110; m_frame.setSize(width, height); m_frame.setVisible(true); m_frame.addWindowListener(this); m_thread = Thread.currentThread(); // Open the local file using file selector /* Popup file dialog (Fileselector) for choosing file to upload (needs FILE access in java security flags)*/ FileDialog fd = new FileDialog(m_frame, "Choisissez un fichier."); fd.setVisible(true); // Added getDirectory() so it can upload from anywhere String selectedFileName = fd.getDirectory() + fd.getFile(); if(selectedFileName == null){ m_frame.setVisible(false); return; } fd.dispose(); // Loads the file in memory for uploading File binaryFile = new File(selectedFileName); long binaryFileLength = binaryFile.length(); // Connect the socket to the selected ip and port m_status.setText("Recherche de l'hôte " + serverNameUrl + " ...") ; m_status.invalidate(); // Try resolving the server name (needs NET access in java security flags) try{ addr = InetAddress.getByName(serverNameUrl); }catch(Exception e){ m_status.setText("Erreur : hôte non trouvé !!!") ; m_status.invalidate(); return; } // Connect the socket // serverPort = 8003; m_status.setText("Connection à " + serverNameUrl + " sur le port " + serverPort + "...") ; m_status.repaint(); try { socket = new Socket(addr, serverPort); } catch(Exception e){ m_status.setText("Erreur : impossible de se connecter au site !!!") ; m_status.invalidate(); return; } m_status.setText("Connecté, création de la sortie : " + fileUploadPath + " Nombre de paramètres :" + nbr_script_param) ; m_status.invalidate(); try { wr = new BufferedOutputStream(socket.getOutputStream()); // uploadPacketSize = socket.getSendBufferSize(); // > java 1.1 ??? Does not seems to work everywhere... } catch (Exception e) { m_status.setText("Erreur : impossible de créer la sortie : " + uploadPath + " !"); m_status.invalidate(); return; } // Prepare what we will send (by constructing the HTTP header) // long contentLenght; String fileHeader ="-----------------------------7d2c0141d01c8\r\n"+ "Content-Disposition: form-data; name=\""+filenameVarName+"\"; filename=\""+selectedFileName+"\"\r\n"+ "Content-type: application/octet-stream\r\n\r\n"; String fileFooter ="\r\n-----------------------------7d2c0141d01c8--\r\n"; int j; String paramName; String paramValue; String encodedParams=""; for(j=0;j<nbr_script_param;j++){ paramName = toSendVarNames[j]; paramValue = toSendVarValues[j]; encodedParams += "-----------------------------7d2c0141d01c8\r\n"+ "Content-Disposition: form-data; name=\""+paramName+"\"\r\n\r\n"+paramValue+"\r\n"; } contentLenght = fileHeader.length() + encodedParams.length() + binaryFileLength + fileFooter.length(); String headerHTTP = ""; headerHTTP += "POST "+scriptPath+" HTTP/1.1\r\n"; headerHTTP += "Accept: image/gif, image/x-xbitmap, image/jpeg, image/pjpeg, application/vnd.ms-powerpoint, application/vnd.ms-excel, application/msword, */*\r\n"; headerHTTP += "Accept-Language: fr,en-us;q=0.7,zh;q=0.3\r\n"; headerHTTP += "Content-Type: multipart/form-data; boundary=---------------------------7d2c0141d01c8\r\n"; headerHTTP += "Accept-Encoding: gzip, deflate\r\n"; headerHTTP += "User-Agent: Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.0; .NET CLR 1.0.3705)\r\n"; headerHTTP += "Host: "+serverNameUrl+":"+serverPort+"\r\n"; // Content length does not include the CR LF headerHTTP += "Content-length: "+(contentLenght-2)+"\r\n"; headerHTTP += "Connection: Close\r\n"; headerHTTP += "Cache-Control: no-cache\r\n\r\n"+encodedParams; // Send the header m_status.setText("Envoi de l'en-tête HTTP..."); m_status.invalidate(); // My upload statistics Date startUploadDate = new Date(); Date curentDate=new Date(); long startMiliSec=startUploadDate.getTime(); long curentMiliSec=curentDate.getTime(); long timeEnlapsed=0; long transferRate=0; long remainingToSend; long eta=0; // Send the HTTP header byte[] plop; int len; plop = headerHTTP.getBytes(); len = headerHTTP.length(); try { wr.write(plop,0,len); } catch (Exception e) { m_status.setText("Erreur : impossible d'envoyer l'en-tête HTTP !") ; m_status.invalidate(); return; } // Send what I call the "file header" plop = fileHeader.getBytes(); len = fileHeader.length(); try { wr.write(plop,0,len); // wr.flush(); } catch (Exception e) { m_status.setText("Erreur : impossible d'envoyer l'en-tête de fichier !") ; m_status.invalidate(); return; } m_status.setText("Envoi des données à " + serverNameUrl + "..."); m_status.invalidate(); m_rateLabel.setText("Transfert : 0 Bps, 0 / " + binaryFileLength + " bytes, ETA: unknown"); m_rateLabel.invalidate(); // Send the file by packets of uploadPacketSize KB long i; int nbrLoop = (int)(binaryFileLength/uploadPacketSize); int lastPacketSize = (int)(binaryFileLength%uploadPacketSize); FileInputStream binaryFileStream; try { binaryFileStream= new FileInputStream(binaryFile); } catch (Exception e) { m_status.setText("Erreur durant la lecture du fichier !") ; m_status.invalidate(); return; } long byteTransfered = 0; byte[] buffer = new byte[uploadPacketSize]; for(i = 0; i < nbrLoop; i++){ try { binaryFileStream.read(buffer,0,uploadPacketSize); wr.write(buffer,0,uploadPacketSize); // wr.flush(); } catch (Exception e) { m_status.setText("Erreur durant l'upload !") ; m_status.invalidate(); return; } byteTransfered += uploadPacketSize; m_bar.percent = ( (byteTransfered*100) / binaryFileLength); if (m_bar.percent > 100) { m_bar.percent = 100; } int frame_width=m_frame.getSize().width; int frame_height=m_frame.getSize().height; if ((frame_width!=m_bar.bar_width) || (frame_height!=m_bar.bar_height)) { m_bar.doresize(frame_width,frame_height); } curentDate = new Date(); curentMiliSec=curentDate.getTime(); timeEnlapsed = curentMiliSec - startMiliSec; if(timeEnlapsed != 0 && byteTransfered != 0){ transferRate = (long)(((byteTransfered * 1000) / timeEnlapsed)/1024); remainingToSend = binaryFileLength - byteTransfered; eta = (long)(remainingToSend / (((byteTransfered * 1000) / timeEnlapsed))); } m_rateLabel.setText("Transfert : " + transferRate + " KBps, " + m_bar.percent+"%, " + byteTransfered + " / " + binaryFileLength+" bytes, ETA: "+eta+" s"); m_top.doLayout(); m_rateLabel.invalidate(); m_bar.invalidate(); m_bar.repaint(); m_center.repaint(); /* try{ Thread.sleep(20); // Helps debugging on very fast links }catch(Exception ex){ }*/ } // Send the last packet if exists if (lastPacketSize != 0) { try { binaryFileStream.read(buffer,0,lastPacketSize); wr.write(buffer,0,lastPacketSize); // wr.flush(); } catch (Exception e) { m_status.setText("Erreur durant la transmission du dernier paquet !") ; m_status.invalidate(); return; } byteTransfered+=lastPacketSize; m_bar.percent = 100; curentDate = new Date(); curentMiliSec = curentDate.getTime(); timeEnlapsed = curentMiliSec - startMiliSec; if (timeEnlapsed != 0) { transferRate = (long)(((byteTransfered * 1000) / timeEnlapsed)/1024); remainingToSend = binaryFileLength - byteTransfered; eta = (long)(remainingToSend / (((byteTransfered * 1000) / timeEnlapsed))); } m_rateLabel.setText("Transfert : " + transferRate+" KB/s, " + byteTransfered+" / " + binaryFileLength + " bytes, ETA: 0"); m_top.doLayout(); m_rateLabel.invalidate(); } // Send the "end of file boundary" m_status.setText("Envoi du pied de page HTTP..."); m_status.invalidate(); plop = fileFooter.getBytes(); len = fileFooter.length(); try { wr.write(plop,0,len); wr.flush(); m_rateLabel.setText("Fin du transfert à " + transferRate + " KB/s, " + binaryFileLength + " bytes in " + (long)(timeEnlapsed/1000) + " secondes"); m_top.doLayout(); m_rateLabel.invalidate(); m_status.setText("Fermeture de la connection..."); m_status.invalidate(); wr.close(); } catch(Exception e) { m_status.setText("Erreur à la fin de l'upload !") ; m_status.invalidate(); return; } // Todo : get and check the HTTP result to KNOW upload was successfull /* int byteRead=0; int ret; InputStreamReader inStream; byte[] anwserBuffer = new byte[uploadPacketSize]; try{ inStream = new InputStreamReader(socket.getInputStream()); }catch(Exception e){ m_status.setText("Error : could get socket read stream !!!"); m_status.invalidate(); return; } String test; try{ while((ret = inStream.read(anwserBuffer,0,512)) != -1){ byteRead+=ret; } }catch(Exception e){ m_status.setText("Error : could not read web server anwser !!!"); m_status.invalidate(); return; }*/ // Close the socket try { socket.close(); } catch(Exception e) { m_status.setText("Erreur : problème de fermeture de la connexion !!!"); m_status.invalidate(); return; } // Display the nice well done message and replace the "Cancel" by a "OK" button m_status.setText("Upload réussi !"); m_top.doLayout(); m_status.repaint(); m_cancelButton.setLabel("OK"); m_cancelButton.repaint(); } public void windowClosing (WindowEvent e) { m_frame.setVisible(false); m_thread.interrupt(); // destroy(); try { socket.close(); } catch(Exception ex){} } public void windowClosed(WindowEvent e) {} public void windowDeactivated(WindowEvent e) {} public void windowActivated(WindowEvent e) {} public void windowDeiconified(WindowEvent e) {} public void windowIconified(WindowEvent e) {} public void windowOpened(WindowEvent e) {} public void actionPerformed (ActionEvent e) { m_frame.setVisible(false); m_thread.interrupt(); // destroy(); try{ socket.close(); } catch(Exception ex) {} } } Et voilà, mais même si je fais deux autres fichiers très simples pour tester, ça ne fonctionne pas. Vive le Québec libre! Et oui, je suis québécoise... |
peux tu essayer ca:
import java.applet.*; import java.awt.*; public class HelloWorldApplet extends Applet implements Runnable { private boolean mustStop; private int red=0, green=0, blue=0; // Démarrage de l'applet public void start() { this.mustStop = false; (new Thread(this)).start(); } // Arrêt de l'applet public void stop() { this.mustStop = true; } // Un nouveau thread pour la réactualisation de l'applet public void run() { while(true) { this.paint(this.getGraphics()); try { Thread.sleep(5); } catch(Exception e) {} if (this.mustStop == true) return; } } // Fait varier aléatoirement une composante de couleur public int randomChange(int composante) { if (Math.random() < 0.5) { if (composante>0) composante--; } else { if (composante<255) composante++; } return composante; } // Dessine de contenu de l'applet public void paint(Graphics gc) { red = this.randomChange(red); green = this.randomChange(green); blue = this.randomChange(blue); gc.setColor(new Color(red, green, blue)); gc.setFont(new Font(gc.getFont().getName(), Font.BOLD, 26)); gc.drawString("Administration",75,35); } } pour voir si cela vient de ton compilo ou de ton code... |
J'ai déjà fait un applet HelloWord pour tester (c'est un classique). Ça fonctionne, mais seulement quand j'ai juste un fichier. Dès que je mets le mot package pour essayer de faire le lien entre les classes, ça plante. Le seul moyen d'avoir plusieurs classes, c'est de mettre toutes mes classes dans le même fichier, d'en mettre une publique et de mettre les autres classes à l'intérieur de cette classe. Mais ce n'est pas super comme méthode... Il doit bien y avoir un moyen d'utiliser plusieurs fichiers.
Vive le Québec libre! Et oui, je suis québécoise...
|
Bonjour,
J'aimerai bien que quelqu'un m'explique à quoi sert le thread dans l'exemple. J'essaie aussi de faire une applet d'upload et je m'inspire de celui-ci. Le thread ne fait qu'instancier un objet où est l'intérêt du thread. Merc |
Would you marry me québecoise?
I'll wait for your answer... |
j'essaye de télécharger le JAR ms.com.security mais j'ai pas réussi
merci de me répondre |