Question

I'm currently working on an App that uploads large PDFs to a server. The app works fine, but sometimes, since the PDFs are so large (25MB), the upload takes a while, and usually after let's say 30 or 40 minutes, I get a "socketException : broken pipe". I believe that this is due to a timeout or disconnect from the server (the server cuts the connection I guess), so I move the upload routine in a loop that has a try / catch. When an exception is thrown, I try to reconnect. It works fine. The upload starts where it stopped and completes.

Problem? Well, since the upload is "broken" in two parts (or more if any connection loss occurs), the file uploaded is broken too! I mean that's definatley normal and I unerstand why that happens, but what I'd like to know is how you can keep the upload on "hold" while trying to reconnect. I just want to be able to do a complete upload even if there are reconnections. I want my PDF to uploaded completely. Here is the code I have :

// 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

I know that my code is not perfect, but that's alright i'm not a perfectionist :)

Any help will be greatly apreciated!

Regards;

Was it helpful?

Solution

I found a replacement method using FP4J llibrary for FTP Uoloads with Java that supports reconnection / append to file.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top