【问题标题】:How can I resume interrupted FTP upload in Python如何在 Python 中恢复中断的 FTP 上传
【发布时间】:2021-05-09 17:14:21
【问题描述】:

我需要手动中断 FTP 上传,然后测试我是否可以恢复上传。我正在使用 Python 的 ftplib 模块。 我试过下面的代码:

# Consider I have logged in using valid ftp user
# File is of 20 MB
counter = 0
file_name = 'test.dat'
ftp_dir = 'test_ftp_dir'

with open(file_address, 'rb') as file:
    ftp.set_debuglevel(2)
    ftp.cwd(ftp_dir)
    ftp.voidcmd('TYPE I')
    with ftp.transfercmd(f'STOR {file_name}', None) as conn:
        while True:
            # Read 1 MB
            buf = file.read(1000000)
            if not buf:
                break
            conn.sendall(buf)
            counter += 1
            if counter == 5:
                # Stop after 5 MB
                LOG.info("STEP-3: Abort client transfer")
                break

# Reading file again and logging again using the ftp user
with open(file_address, 'rb') as file:
    ftp.set_debuglevel(2)
    ftp.cwd(ftp_dir)
    ftp.voidcmd('TYPE I')
    ftp.storbinary(f'STOR {file_name}', file, rest=ftp.size(file_name))

不是从 5 MB 重新开始上传,而是在附加到原始文件的同时发送完整文件。假设我发送了 5 MB 的文件,然后我可以看到 5 MB 的文件,当我尝试恢复它时,它会发送整个 20 MB 的文件,使其成为总共 25 MB 的文件。请帮助我。谢谢。

【问题讨论】:

    标签: python python-3.x ftp ftplib


    【解决方案1】:

    在开始传输之前,您必须将源本地文件寻找到重启位置:

    # Reading file again and logging again using the ftp user
    with open(file_address, 'rb') as file:
        rest = ftp.size(file_name)
        file.seek(rest)
        ftp.cwd(ftp_dir)
        ftp.storbinary(f'STOR {file_name}', file, rest=rest)
    

    ftplib 不会为您寻找文件,这会限制它的使用。在某些情况下,您不希望它寻找。还有一些类似文件的对象不支持查找。


    有关可恢复 FTP 上传的完整代码,请参阅:
    Handling disconnects in Python ftplib FTP transfers file upload

    【讨论】:

      猜你喜欢
      • 2017-06-06
      • 2019-03-02
      • 2017-11-30
      • 1970-01-01
      • 1970-01-01
      • 2013-12-16
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多