Boto S3上传时文本文件内容丢失

时间:2015-08-04 14:30:01

标签: python amazon-s3 boto

我一直在将文本文件上传到S3,我遇到了这个有趣的错误:文件并不总是上传,只是文件名。所以有时上传整个文件,有时我在S3上有一个0字节的文件。我一直在使用这个教程:

http://stackabuse.com/example-upload-a-file-to-aws-s3/

这是我一直在使用的代码(减去键等):

#NOTE Section 8: Uploading to Amazon

AWS_ACCESS_KEY = ''
AWS_ACCESS_SECRET_KEY = ''

filea = open(date + '.txt', 'r+')

key = filea.name
bucket = ''





import os
import boto
from boto.s3.key import Key


##Beginning of function
def upload_to_s3(aws_access_key_id, aws_secret_access_key, filea, bucket, key, callback=None, md5=None, reduced_redundancy=False, content_type=None):
    """
    Uploads the given file to the AWS S3
    bucket and key specified.

    callback is a function of the form:

    def callback(complete, total)

    The callback should accept two integer parameters,
    the first representing the number of bytes that
    have been successfully transmitted to S3 and the
    second representing the size of the to be transmitted
    object.

    Returns boolean indicating success/failure of upload.
    """

    #   try:
     #      size = os.fstat(file.fileno()).st_size
    #   except:
            # Not all file objects implement fileno(),
            # so we fall back on this
     #      file.seek(0, os.SEEK_END)
      #     size = file.tell()

    conn = boto.connect_s3(aws_access_key_id, aws_secret_access_key)
    bucket = conn.get_bucket(bucket, validate=False)
    k = Key(bucket)
    k.key = key

    print k.key

    #if content_type:
     #  k.set_metadata('Content-Type', content_type)
    sent = k.set_contents_from_file(filea, cb=callback, md5=md5, reduced_redundancy=reduced_redundancy, rewind=True)

    print sent

        # Rewind for later use
    filea.seek(0)
    #print size

##End of function



upload_to_s3(AWS_ACCESS_KEY, AWS_ACCESS_SECRET_KEY, filea, bucket, key)
os.remove(date + '.txt')

现在有一些关于我的内容的信息:代码的前面部分写出了一个文本文件,有多行段落,但仍然是一个用+权限创建的文本文件。该文件使用(date +'.txt')命名,并且在代码的前面部分中没有使用.close()关闭,除非python解释器执行了一些我不知道的子进程(.close()给了我一些问题所以我只是把它打开了,因为我的代码的最后一行在这里删除它)。

我已经尝试循环上传过程,但似乎文件没有正确读取。我做错了什么?

1 个答案:

答案 0 :(得分:0)

Boto在开始上传之前不会将文件回卷到0。如果传递给k.set_contents_from_file的文件指针不在文件的开头,则不会发送从开头到文件到当前位置的任何数据(由fp.tell()报告)。这是设计的,我不认为这是boto中的错误。

如果您想确保将整个文件上传到S3,请确保文件指针位于文件的开头,然后再将其传递给boto。从上面显示的代码中,您在上传后进行倒带,但不是之前。