0

突然,当我将文件上传到 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()
            ...
4

1 回答 1

1

根据您所描述的行为,我敢打赌文件指针位于末尾,因为您只是显式调用了该storage.save()函数。通过两次读取文件,您将一无所获。

f = StringIO.StringIO('foobar')
f.read() # out 'foobar'
f.read() # out ''
f.seek(0) 
f.read() # out 'foobar'
于 2012-11-04T19:32:27.933 回答