当我将文件上传到S3时,突然上传为0字节。
我不确定为什么这会突然发生,因为它之前的工作正常。这是我的代码:
def store_in_s3_avatar(pathtofile, avatarimage, filename, user):
conn = S3Connection(settings.AWS_ACCESS_KEY_ID, settings.AWS_SECRET_ACCESS_KEY)
b = conn.create_bucket('mybucket')
mime = mimetypes.guess_type(filename)[0]
k = Key(b)
k.key = "/media/avatars/%s/%s" % (user,filename)
k.set_metadata("Content-Type", mime)
k.set_contents_from_string(avatarimage)
k.set_acl("public-read")
return pathtofile
以下是调用此函数的views.py片段:
if request.method == "POST":
updated = False
if 'avatar' in request.FILES:
path = avatar_file_path(user=request.user,
filename=request.FILES['avatar'].name)
avatar = Avatar(
user = request.user,
primary = True,
avatar = path,
)
new_file = avatar.avatar.storage.save(path, request.FILES['avatar'])
avatarcontent = request.FILES['avatar']
filename = request.FILES['avatar'].name
avatarimage = avatarcontent.read()
user=request.user
avatar.avatar = store_in_s3_avatar(path, avatarimage, filename, user)
avatar.save()
...
答案 0 :(得分:1)
根据您描述的行为,我打赌文件指针在最后,因为您只是明确地调用了storage.save()
函数。通过两次读取文件,你什么也得不到。
f = StringIO.StringIO('foobar')
f.read() # out 'foobar'
f.read() # out ''
f.seek(0)
f.read() # out 'foobar'