Suddenly when I upload a file to S3 it is uploading as 0 bytes.
I’m not sure why this is suddenly happening since it was working fine earlier. Here’s my code:
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
Here’s the views.py snippet that calls this function:
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()
...
Based on the behavior you’re describing, I bet the file pointer is at the end because you just explicitly called the
storage.save()function. By reading a file twice, you’ll get nothing.