我正在获取文件大小并将其上传到S3:
def transfer_file_from_ftp_to_s3(bucket_name, ftp_file_path, s3_file_path, ftp_username, ftp_password, chunk_size):
ftp_connection = open_ftp_connection(FTP_HOST, int(FTP_PORT), ftp_username, ftp_password)
ftp_file = ftp_connection.file(ftp_file_path, 'r')
s3_connection = boto3.client('s3')
ftp_file_size = ftp_file._get_size()
if ftp_file_size <= int(chunk_size):
#upload file in one go
print('Transferring complete File from FTP to S3...')
ftp_file_data = ftp_file.read()
s3_connection.upload_fileobj(ftp_file_data, bucket_name, s3_file_path)
print('Successfully Transferred file from FTP to S3!')
ftp_file.close()
我在下面收到此错误消息:
Transferring complete File from FTP to S3...
Traceback (most recent call last):
File "/Users/admin/anaconda2/lib/python2.7/site-packages/boto3/s3/inject.py", line 520, in upload_fileobj
raise ValueError('Fileobj must implement read')
ValueError: Fileobj must implement read
你能给我一些指导吗?谢谢。
答案 0 :(得分:3)
您正在上传从文件对象读取的数据,但是方法名称建议您应该传递文件对象本身:
s3_connection.upload_fileobj(ftp_file, bucket_name, s3_file_path)
答案 1 :(得分:1)
关于如何上传数据的字节表示形式的更一般的答案将使用IO包。
s3 = boto3.resource('s3')
bucket = s3.Bucket(name="your-bucket-name-here")
data = requests.get('https://www.google.de/images/branding/googlelogo/1x/googlelogo_color_272x92dp.png').content
bucket.upload_fileobj(io.BytesIO(data), 'googleLogoTestUpload.png')
我正在使用the request package,必须先使用pip下载。 该答案基于jwodder的answer on another question
答案 2 :(得分:0)
我用了这个:s3_connection.upload_fileobj(ftp_file, bucket_name, s3_file_path)
但由于它上传了一个空文件而无法正常工作(试图以各种方式读取文件)。
最后尝试了下面的代码,它的工作就像一个魅力!
仅供参考,我已使用paramiko
打开FTP连接。
ftp_file = ftp_connection.file(ftp_file_path, 'r')
ftp_file_data = ftp_file.read()
s3 = boto3.resource('s3')
s3.Object(bucket_name, s3_file_path).put(Body=ftp_file_data)