【问题标题】:FTP library error: got more than 8192 bytesFTP 库错误:超过 8192 字节
【发布时间】:2015-03-16 23:24:32
【问题描述】:

Python 在上传大于 8192 字节的文件时失败。例外只是“得到了超过 8192 个字节”。有没有上传大文件的解决方案。

try:
    ftp = ftplib.FTP(str_ftp_server )
    ftp.login(str_ftp_user, str_ftp_pass)
except Exception as e:
    print('Connecting ftp server failed')
    return False

try:
    print('Uploading file ' + str_param_filename)
    file_for_ftp_upload = open(str_param_filename, 'r')
    ftp.storlines('STOR ' + str_param_filename, file_for_ftp_upload)

    ftp.close()
    file_for_ftp_upload.close()
    print('File upload is successful.')
except Exception as e:
    print('File upload failed !!!exception is here!!!')
    print(e.args)
    return False

return True

【问题讨论】:

  • 文件是否包含文本?如果没有,您可能希望以二进制模式打开并使用ftp.storbinary()

标签: python file-upload ftp


【解决方案1】:

我有一个类似的问题,并通过增加 ftplib 的 maxline 变量的值来解决它。您可以将其设置为您希望的任何整数值。它表示文件中每行的最大字符数。这会影响上传和下载。

根据 Alex Martelli 的回答,我建议在大多数情况下使用 ftp.storbinary,但这不是我的选择(不是常态)。

ftplib.FTP.maxline = 16384    # This is double the default value

在开始文件传输之前随时调用该行。

【讨论】:

  • 这非常有效。非常感谢。这也适用于 retrlines()。
【解决方案2】:

storlines 一次读取一行文本文件,每行的最大大小为 8192。作为上传功能的核心,您可能最好使用:

with open(str_param_filename, 'rb') as ftpup:
    ftp.storbinary('STOR ' + str_param_filename, ftpup)
    ftp.close()

这以二进制形式读取和存储,一次一个块(默认为 8192),但应该适用于任何大小的文件。

【讨论】:

  • 如果发送和接收系统属于不同类型,请谨慎使用此解决方案。以二进制形式发送不会在不同类型的系统之间自动转换字符编码等。二进制和文本模式可能有不同的行为。
  • @stenix,如果您不想按原样实际上传文件(这正是 OP 暗示“上传文件”的所有请求!),而是需要应用任何类型翻译,那么你当然需要与上传不同的代码——当然,这取决于你需要什么翻译。
猜你喜欢
  • 2018-08-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-03-03
  • 1970-01-01
  • 1970-01-01
  • 2010-11-09
相关资源
最近更新 更多