【发布时间】:2015-08-04 22:59:25
【问题描述】:
我一直在将文本文件上传到 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')
现在关于我输入的内容的一些信息:代码的早期部分写出一个文本文件,有多行段落,但仍然是一个使用 a+ 权限创建的文本文件。该文件使用 (date + '.txt') 命名,并且不会在代码的早期部分中使用 .close() 关闭,除非 python 解释器执行了一些我不知道的子进程 (.close()给了我一些问题,所以我把它打开了,因为我的代码的最后一行在这里删除了它)。
我尝试循环上传过程,但文件似乎没有正确读取。我做错了什么?
【问题讨论】: