2016-12-15 125 views
0

我試圖將文件上傳到FTP服務器的Java:將文件上傳到FTP服務器

正如我在這裏How do you upload a file to an FTP server?發現,我有這樣的代碼:

FTPClient client = new FTPClient(); 
FileInputStream fis = null; 

try { 
    client.connect("IP"); 
    client.login("user", "pwd"); 
    client.changeWorkingDirectory("https://stackoverflow.com/a/b/c/"); 

    // Create an InputStream of the file to be uploaded 
    String filePath = file.getPath(); 
    fis = new FileInputStream(filePath); 
    String fileName = file.getName();        

    // Store file to server 
    client.storeFile(fileName, fis); 
    client.logout(); 

} catch (Exception e) { 
    e.printStackTrace(); 
} finally { 
    try { 
    if (fis != null) { 
     fis.close(); 
    } 
    client.disconnect(); 
    } catch (Exception e) { 
    e.printStackTrace(); 
    } 
} 

當我運行它,創建文件,其中預期,但它是空的(0 KB)

的寫作過程也需要相當多的時間...

我在做什麼錯?

+0

查看這段代碼是否正確:String filePath = file.getPath(); fis = new FileInputStream(filePath);你如何創建文件對象?它可能會很慢,因爲你的互聯網連接速度慢或者你的ftp服務器很慢......可能是 – thepaulo

+0

任何錯誤/異常? –

+0

您可以使用獨立的FTP客戶端將相同的文件上傳到同一個服務器和目錄嗎? –

回答

-1

看這篇文章 Apache Commons FTP problems 你需要設置文件類型和tranfor模式來使這項工作。

+0

是什麼讓你認爲錯誤的傳輸模式會導致上傳的文件變空? –

+0

我已添加文件類型(BINARY_FILE_TYPE)和轉移模式(STREAM_TRANSFER_MODE),但問題仍然存在 – Maik