我必须使用JavaSwing将文件上传到服务器
我对荡秋千很陌生。 我需要使用JavaSwing将一个文件上传到Jboss服务器。我怎样才能完成这项任务我必须使用JavaSwing将文件上传到服务器,java,http,swing,Java,Http,Swing,我对荡秋千很陌生。 我需要使用JavaSwing将一个文件上传到Jboss服务器。我怎样才能完成这项任务 谢谢,Max已经提到Swing是一个UI库。 您必须创建HTTP post并将文件写入输出流,即执行以下操作: URL url = new URL("http://host/filehandler"); HttpURLConnection con = (HttpURLConnection)url.openConnection(); con.setDoInput(true); con.setD
谢谢,Max已经提到Swing是一个UI库。 您必须创建HTTP post并将文件写入输出流,即执行以下操作:
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);
}
显然
http://host/filehandler
应该映射到准备好接收此帖子并处理它的内容。例如,实现doPost()
并将流另存为文件的servlet。使用JFileChooser并选择要上载的文件后,必须连接到服务器。您的服务器必须运行ftp服务器。你必须有一个帐户和密码。从apache获取commons-net-2.2.jar
,以便能够创建FTPClient
您将在此处找到有关FTPClient的更多信息:
您的代码必须如下所示:
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());
}
}
Swing与文件上载无关,您需要一些Java HTTP客户端,例如:感谢您的回答,我正在使用JFileChooser()类从我的系统中选择文件,现在我需要将该文件上载到服务器。。。我该怎么做。。。