我目前正在开发一款可以将大型 PDF 文件上传到服务器的应用程序。该应用程序运行良好,但有时,由于 PDF 太大 (25MB),上传需要一段时间,通常在 30 或 40 分钟后,我会收到“socketException:管道损坏”。我相信这是由于超时或与服务器断开连接(我猜是服务器切断了连接),所以我将上传例程移动到一个具有 try/catch 的循环中。当抛出异常时,我尝试重新连接。它工作正常。上传从停止处开始并完成。
问题?好吧,由于上传被“破坏”为两部分(如果发生任何连接丢失,则更多),上传的文件也被破坏了!我的意思是这绝对是正常的,我不明白为什么会这样,但我想知道的是如何在尝试重新连接时保持上传“暂停”。我只想即使有重新连接也能完成完整的上传。我希望我的 PDF 完整上传。这是我的代码:
// In
inputStream = new FileInputStream(localFile);
// For upload loop
byte[] bytesIn = new byte[4096];
int read = 0;
// Loop until job is not completed (will try to reconnect if any exception is thrown)
boolean completed = false;
while (!completed){
try{
// Out
OutputStream outputStream = ftpClient.storeFileStream(remoteFile);
// Transfer
while ((read = inputStream.read(bytesIn)) != -1) {
outputStream.write(bytesIn, 0, read);
transfered += read;
}
// Closing streams
inputStream.close();
outputStream.close();
// Final information
completed = ftpClient.completePendingCommand();
if (completed) System.out.println("Done");
else System.out.println("Failure.");
completed = true;
} // end try
catch (Exception e) {
// Telling the user
System.out.println("Trying to reconnect...");
Thread.sleep(1000);
// Try to reconnect
ftpClient.connect(server, port);
success = ftpClient.login(user, pass);
if (success) {
System.out.println("Connection : OK");
Thread.sleep(1000);
} else {
System.out.println("Failed to connect");
}
// Set passive mode and file type to binary
ftpClient.enterLocalPassiveMode();
ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE);
} // end catch
} // end loop
我知道我的代码并不完美,但没关系我不是完美主义者:)
我们将不胜感激任何帮助!
问候;
最佳答案
我找到了一种使用 FP4J llibrary 的替代方法,用于 FTP Uoloads 和支持重新连接/附加到文件的 Java。
关于Java FTPCLient : upload file, 连接丢失后重新连接?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16365837/