Java Applet Upload
Cyber Liz
Messages postés
64
Date d'inscription
Statut
Membre
Dernière intervention
-
Pseudo2K -
Pseudo2K -
Bonjour,
Quelqu'un a déjà fait un applet pour uploader des fichiers? Le mien semble lire le fichier à uploader mais il ne l'écrit pas sur le serveur. C'est un code que j'ai trouvé sur internet et que j'ai modifié. J'ai créé le certificat alors ce n'est pas un problème de sécurité. Il n'y a aucune erreur affichée dans la console java. Je vous donne un bout de code (un grand bout) de la classe qui upload.
public uploadWindow (String filenameVarName, String uploadPath) {
// Change le titre de la fenêtre (doit être la première ligne du constructeur)
super("Transfert");
getURL(uploadPath);
// CREATE THE WINDOW INTERFACE
// Create the frame (called frame but is a detached window);
c = getContentPane();
c.setLayout(new BorderLayout());
c.add(m_top, BorderLayout.NORTH);
c.add(m_center, BorderLayout.CENTER);
c.add(m_bottom, BorderLayout.SOUTH);
// Add all the cancel button
m_cancelButton = new JButton("Cancel");
m_bottom.add(m_cancelButton, BorderLayout.CENTER);
m_cancelButton.addActionListener(this);
// Add the status label to it
m_status = new JLabel("Initialisation...");
m_top.add(m_status, BorderLayout.WEST);
// Add the transfer rate string
m_rateLabel = new JLabel("Transfert du fichier " + fd.getFile() + ": 0 Bps, 0%, 0 / 0 bytes");
m_top.add(m_rateLabel, BorderLayout.EAST);
m_bar = new progress();
m_center.add(m_bar);
// Get the progress indicator bounds
progressRect = m_center.getBounds();
// Show the frame
int width = 750;
int height = 110;
setSize(width, height);
setVisible(true);
show();
addWindowListener(this);
uploadButton.setEnabled(false);
choisir.setEnabled(false);
afficher = new Affichage();
afficher.start();
m_thread = Thread.currentThread();
// Added getDirectory() so it can upload from anywhere
String selectedFileName = fd.getDirectory() + fd.getFile();
if (selectedFileName == null) {
dispose();
return;
}
// 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 + " ...") ;
// 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é !!!") ;
return;
}
// Connect the socket
m_status.setText("Connection à " + serverNameUrl + " sur le port " +
serverPort + "...") ;
try {
socket = new Socket(adresse, serverPort);
} catch(Exception e) {
m_status.setText("Erreur : impossible de se connecter au site !!!") ;
return;
}
m_status.setText("Connecté, création de la sortie : " + fileUploadPath) ;
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 + " !");
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";
// Paramètres
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() + binaryFileLength + fileFooter.length();
String headerHTTP = "";
headerHTTP += "POST " + scriptPath + " HTTP/1.1\r\n";
headerHTTP += "Accept: image/gif, image/x-xbitmap, image/jpeg, image/jpg, 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";
/* Send the header */
m_status.setText("Envoi de l'en-tête HTTP...");
// 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 eta = 0;
long remainingToSend;
// 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 !") ;
return;
}
// Send what I call the "file header"
plop = fileHeader.getBytes();
len = fileHeader.length();
try {
wr.write(plop, 0, len);
} catch (Exception e) {
m_status.setText("Erreur : impossible d'envoyer l'en-tête de fichier !") ;
return;
}
m_status.setText("Envoi des données à " + serverNameUrl + "...");
m_rateLabel.setText("Transfert : 0 Bps, 0 / " + binaryFileLength +
" bytes, ETA: unknown");
// 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 !") ;
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);
} catch (Exception e) {
m_status.setText("Erreur durant l'upload !") ;
return;
}
byteTransfered += uploadPacketSize;
m_bar.percent = ((byteTransfered * 100) / binaryFileLength);
if (m_bar.percent > 100) {
m_bar.percent = 100;
}
int frame_width = getSize().width;
int frame_height = 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();
}
// Envoyer le dernier paquet s'il existe
if (lastPacketSize != 0) {
try {
binaryFileStream.read(buffer,0,lastPacketSize);
wr.write(buffer,0,lastPacketSize);
} catch (Exception e) {
m_status.setText("Erreur durant la transmission du dernier paquet !") ;
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();
}
// Send the "end of file boundary"
m_status.setText("Envoi du pied de page HTTP...");
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_status.setText("Fermeture de la connection...");
wr.close();
} catch(Exception e) {
m_status.setText("Erreur à la fin de l'upload !") ;
return;
}
// Close the socket
try {
socket.close();
} catch(Exception e) {
m_status.setText("Erreur : problème de fermeture de la connexion !!!");
return;
}
new MsgBox("fileUploadPath : " + fileUploadPath + " serverNameUrl : " + serverNameUrl + " scriptPath : " + scriptPath + " addr : " + addr);
// Display the nice well done message and replace the "Cancel" by a "OK" button
if (verifierUpload()) {
m_status.setText("Transfert réussi !");
afficher.interrupt();
} else {
m_status.setText("Erreur durant le transfert !");
afficher.interrupt();
}
m_top.doLayout();
m_cancelButton.setText("OK");
m_cancelButton.repaint();
m_cancelButton.invalidate();
}
/**
* Vérifier que le fichier a bien été transféré.
* Retourne true si le fichier a été transféré correctement et false s'il y a eu une erreur.
*/
private boolean verifierUpload() {
boolean fUpload = true;
int byteRead = 0;
int ret;
InputStreamReader inStream;
//byte[] anwserBuffer = new byte[uploadPacketSize];
char[] anwserBuffer = new char[uploadPacketSize];
try {
inStream = new InputStreamReader(socket.getInputStream());
try {
while((ret = inStream.read(anwserBuffer, 0, 512)) != -1) {
byteRead += ret;
}
} catch (Exception e) {
m_status.setText("Erreur : impossible de lire la réponse du serveur !!!");
fUpload = false;
}
} catch (Exception e) {
m_status.setText("Erreur : impossible de se connecter (socket read stream) !!!");
fUpload = false;
}
return fUpload;
}
Aidez-moi!! Merci!
Vive le Québec libre! Et oui, je suis québécoise...
Quelqu'un a déjà fait un applet pour uploader des fichiers? Le mien semble lire le fichier à uploader mais il ne l'écrit pas sur le serveur. C'est un code que j'ai trouvé sur internet et que j'ai modifié. J'ai créé le certificat alors ce n'est pas un problème de sécurité. Il n'y a aucune erreur affichée dans la console java. Je vous donne un bout de code (un grand bout) de la classe qui upload.
public uploadWindow (String filenameVarName, String uploadPath) {
// Change le titre de la fenêtre (doit être la première ligne du constructeur)
super("Transfert");
getURL(uploadPath);
// CREATE THE WINDOW INTERFACE
// Create the frame (called frame but is a detached window);
c = getContentPane();
c.setLayout(new BorderLayout());
c.add(m_top, BorderLayout.NORTH);
c.add(m_center, BorderLayout.CENTER);
c.add(m_bottom, BorderLayout.SOUTH);
// Add all the cancel button
m_cancelButton = new JButton("Cancel");
m_bottom.add(m_cancelButton, BorderLayout.CENTER);
m_cancelButton.addActionListener(this);
// Add the status label to it
m_status = new JLabel("Initialisation...");
m_top.add(m_status, BorderLayout.WEST);
// Add the transfer rate string
m_rateLabel = new JLabel("Transfert du fichier " + fd.getFile() + ": 0 Bps, 0%, 0 / 0 bytes");
m_top.add(m_rateLabel, BorderLayout.EAST);
m_bar = new progress();
m_center.add(m_bar);
// Get the progress indicator bounds
progressRect = m_center.getBounds();
// Show the frame
int width = 750;
int height = 110;
setSize(width, height);
setVisible(true);
show();
addWindowListener(this);
uploadButton.setEnabled(false);
choisir.setEnabled(false);
afficher = new Affichage();
afficher.start();
m_thread = Thread.currentThread();
// Added getDirectory() so it can upload from anywhere
String selectedFileName = fd.getDirectory() + fd.getFile();
if (selectedFileName == null) {
dispose();
return;
}
// 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 + " ...") ;
// 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é !!!") ;
return;
}
// Connect the socket
m_status.setText("Connection à " + serverNameUrl + " sur le port " +
serverPort + "...") ;
try {
socket = new Socket(adresse, serverPort);
} catch(Exception e) {
m_status.setText("Erreur : impossible de se connecter au site !!!") ;
return;
}
m_status.setText("Connecté, création de la sortie : " + fileUploadPath) ;
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 + " !");
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";
// Paramètres
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() + binaryFileLength + fileFooter.length();
String headerHTTP = "";
headerHTTP += "POST " + scriptPath + " HTTP/1.1\r\n";
headerHTTP += "Accept: image/gif, image/x-xbitmap, image/jpeg, image/jpg, 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";
/* Send the header */
m_status.setText("Envoi de l'en-tête HTTP...");
// 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 eta = 0;
long remainingToSend;
// 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 !") ;
return;
}
// Send what I call the "file header"
plop = fileHeader.getBytes();
len = fileHeader.length();
try {
wr.write(plop, 0, len);
} catch (Exception e) {
m_status.setText("Erreur : impossible d'envoyer l'en-tête de fichier !") ;
return;
}
m_status.setText("Envoi des données à " + serverNameUrl + "...");
m_rateLabel.setText("Transfert : 0 Bps, 0 / " + binaryFileLength +
" bytes, ETA: unknown");
// 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 !") ;
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);
} catch (Exception e) {
m_status.setText("Erreur durant l'upload !") ;
return;
}
byteTransfered += uploadPacketSize;
m_bar.percent = ((byteTransfered * 100) / binaryFileLength);
if (m_bar.percent > 100) {
m_bar.percent = 100;
}
int frame_width = getSize().width;
int frame_height = 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();
}
// Envoyer le dernier paquet s'il existe
if (lastPacketSize != 0) {
try {
binaryFileStream.read(buffer,0,lastPacketSize);
wr.write(buffer,0,lastPacketSize);
} catch (Exception e) {
m_status.setText("Erreur durant la transmission du dernier paquet !") ;
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();
}
// Send the "end of file boundary"
m_status.setText("Envoi du pied de page HTTP...");
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_status.setText("Fermeture de la connection...");
wr.close();
} catch(Exception e) {
m_status.setText("Erreur à la fin de l'upload !") ;
return;
}
// Close the socket
try {
socket.close();
} catch(Exception e) {
m_status.setText("Erreur : problème de fermeture de la connexion !!!");
return;
}
new MsgBox("fileUploadPath : " + fileUploadPath + " serverNameUrl : " + serverNameUrl + " scriptPath : " + scriptPath + " addr : " + addr);
// Display the nice well done message and replace the "Cancel" by a "OK" button
if (verifierUpload()) {
m_status.setText("Transfert réussi !");
afficher.interrupt();
} else {
m_status.setText("Erreur durant le transfert !");
afficher.interrupt();
}
m_top.doLayout();
m_cancelButton.setText("OK");
m_cancelButton.repaint();
m_cancelButton.invalidate();
}
/**
* Vérifier que le fichier a bien été transféré.
* Retourne true si le fichier a été transféré correctement et false s'il y a eu une erreur.
*/
private boolean verifierUpload() {
boolean fUpload = true;
int byteRead = 0;
int ret;
InputStreamReader inStream;
//byte[] anwserBuffer = new byte[uploadPacketSize];
char[] anwserBuffer = new char[uploadPacketSize];
try {
inStream = new InputStreamReader(socket.getInputStream());
try {
while((ret = inStream.read(anwserBuffer, 0, 512)) != -1) {
byteRead += ret;
}
} catch (Exception e) {
m_status.setText("Erreur : impossible de lire la réponse du serveur !!!");
fUpload = false;
}
} catch (Exception e) {
m_status.setText("Erreur : impossible de se connecter (socket read stream) !!!");
fUpload = false;
}
return fUpload;
}
Aidez-moi!! Merci!
Vive le Québec libre! Et oui, je suis québécoise...
A voir également:
- Java Applet Upload
- Waptrick java football - Télécharger - Jeux vidéo
- Jeux java itel - Télécharger - Jeux vidéo
- Eclipse java - Télécharger - Langages
- Java apk - Télécharger - Langages
- Waptrick java voiture - Télécharger - Jeux vidéo
1 réponse
T'as des exemples de scripts (PHP, JSP ...) coté serveur pour l'upload:
http://www.jfileupload.com/products/tools/index.html
Et l'applet JFileUpload qui va avec pour tester:
http://www.jfileupload.com/products/jfileupload/index.html
--
http://www.jfileupload.com/products/tools/index.html
Et l'applet JFileUpload qui va avec pour tester:
http://www.jfileupload.com/products/jfileupload/index.html
--