Reputation: 15
I am very much new to swing . I need to upload a file to the Jboss server using a java swing . How can i go about in the task ?
Thanks
Upvotes: 0
Views: 3530
Reputation: 13728
Once you have used your JFileChooser and have selected the file you wish to upload you must connect to the server. Your server must have an ftp-server running. You have to have an account and password. Get the commons-net-2.2.jar
from apache, in order to be able to create FTPClient.
Here you will find more about FTPClient:
http://commons.apache.org/net/apidocs/org/apache/commons/net/ftp/FTPClient.html
Your code must look like this:
FTPClient client = new FTPClient();
FileInputStream fis = null;
try {
client.connect("192.168.1.123");
client.login("myaccount", "myPasswd");
int reply = client.getReplyCode();
if (!client.isConnected()) {
System.out.println("FTP server refused connection." + reply);
client.disconnect();
System.exit(1);
} else {
System.out.println("FTP server connected." + reply);
}
// Create an InputStream for the file to be uploaded
String filename = "sp2t.c";
fis = new FileInputStream(filename);
// Store file to server
client.storeFile(filename, fis);
client.logout();
} catch (IOException e) {
System.out.println(e.getMessage());
} finally {
try {
if (fis != null) {
fis.close();
}
client.disconnect();
} catch (IOException e) {
System.out.println(e.getMessage());
}
}
Upvotes: 0
Reputation: 115328
As Max already mentioned Swing is a UI library. You have to create HTTP post and write your file into the output stream, i.e. do something like:
URL url = new URL("http://host/filehandler");
HttpURLConnection con = (HttpURLConnection)url.openConnection();
con.setDoInput(true);
con.setDoOutput(true);
con.setUseCaches(false);
con.setRequestMethod("POST");
InputStream in = new FileInputStream(filePath);
OutputStream out = con.getOutputStream();
byte[] buffer = new byte[4096];
while (-1 != (n = in.read(in))) {
out.write(buffer, 0, n);
}
Obviously http://host/filehandler
should be mapped to something that is ready to receive this post and deal with it. For example servlet that implements doPost()
and saves the stream as file.
Upvotes: 1