2010-12-23 79 views

回答

1

正如馬克斯已經提到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並將該流保存爲文件。

0

使用過JFileChooser並選擇了要上傳的文件後,您必須連接到服務器。您的服務器必須運行一個ftp服務器。你必須有一個帳戶和密碼。從apache獲取commons-net-2.2.jar,以便能夠創建FTPClient。

在這裏,你會發現更多的有關FTPClient:

http://commons.apache.org/net/apidocs/org/apache/commons/net/ftp/FTPClient.html

你的代碼必須是這樣的:

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()); 
    } 
} 
相關問題