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...