使用 JSch 库的上传重试机制

Upload retry mechanism using JSch library

我有一个文件要上传(比如 abc.pdf)。我第一次想将此文件作为临时文件上传(比如 abc.pdf.temp)。然后,如果文件成功传输(完全传输),那么我需要将其重命名为原来的名称(abc.pdf)。但是如果文件没有完全传输,那么我需要删除我最初上传的临时文件,因为我不想在服务器中保留损坏的文件。使用这个 JSch 库可以做到这一点吗?下面是示例代码。这段代码对实现这个有意义吗?

示例代码:

originalFile = 'abc.pdf';
tempFile = 'abc.pdf.temp';
fileInputStream = createobject("java", "java.io.FileInputStream").init('C:\abc.pdf'); 
SftpChannel.put(fileInputStream,tempFile);

// Comparing remote file size with local file
if(SftpChannel.lstat(tempFile).getSize() NEQ localFileSize){
    // Allow to Resume the file transfer since the file size is different
    SftpChannel.put(fileInputStream,tempFile,SftpChannel.RESUME); 
    if(SftpChannel.lstat(tempFile).getSize() NEQ localFileSize){
       // Check again if the file is not fully transferred (During RESUME) then
       // deleting the file since dont want to keep a corrupted file in the server.
       SftpChannel.rm(tempFile);
    }
}else{//assuming file is fully transferred
    SftpChannel.rename(tempFile ,originalFile);
}
  1. put 完成而不抛出后,文件大小不匹配的可能性很小。这几乎不可能发生。即使它发生了,调用 RESUME 也没什么意义。如果出现 put 未检测到的灾难性错误,RESUME 可能无济于事。

    而且即使你想用RESUME试一下,试一次也没有意义。如果您认为重试有意义,就必须不断重试直到成功,而不是一次。

  2. 你应该捕获异常并且resume/delete/whatever。这是主要的恢复机制。这比 1 发生的可能性高 100 倍。