简体   繁体   English

将图像上传到S3(boto + GAE)

[英]Uploading image to S3 (boto + GAE)

I'm trying to get s3 (using boto) setup with my GAE python app to store images uploaded by users. 我正在尝试使用我的GAE python应用程序获取s3(使用boto)设置来存储用户上传的图像。 Currently I get the following error: 目前我收到以下错误:

File "/Users/phyzikz/project/boto/s3/key.py", line 936, in set_contents_from_file spos = fp.tell()
AttributeError: 'str' object has no attribute 'tell'

I'm at a loss for why this is happening – the file uploaded should be a png. 我不知道为什么会发生这种情况 - 上传的文件应该是png。 Here's the code that makes the upload: 这是上传的代码:

class Settings(Handler):
    def get(self):
        self.render('settings.html')

    def post(self):
        image = self.request.get('image')

        if image:
            connection = S3Connection('<ak>','<sak>')
            bucket = connection.create_bucket('<s3bucket>')
            k = Key(bucket)
            k.key = '/pictures/users/'+ str(self.user.key().id())
            k.set_contents_from_file(image)

If it helps, while debugging it worked beautifully when substituting set_contents_from_file(image) with set_contents_from_string('some string'). 如果它有帮助,在调试时,当用set_contents_from_string('some string')替换set_contents_from_file(image)时,它工作得非常好。 I must be missing something simple. 我一定很遗憾。 Here's the html: 这是html:

<form method='post' action='/settings' enctype='multipart/form-data'>
    <input type='file' name='image'>
    <input type='submit'>
</form>

disclaimer: I'm new to both python and SO (this is my first question!) Any edits to improving the phrasing of the question if necessary would be appreciated. 免责声明:我是python和SO的新手(这是我的第一个问题!)如果有必要,任何改进问题措辞的编辑都将受到赞赏。

You will need to wrap image in a StringIO instance so it looks like a file object 您需要将图像包装在StringIO实例中,使其看起来像文件对象

Python 2.7.2+ (default, Oct  4 2011, 20:03:08) 
[GCC 4.6.1] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> x = "123"
>>> from StringIO import StringIO
>>> y = StringIO(x)
>>> y.tell()
0
>>> 

So in your case you would 所以在你的情况下,你会

k.set_contents_from_file(StringIO(image))

If you can put the code (in the method: set_contents_from_file inside the Key class ) where you have defined or assigned fp , we can help better. 如果您可以将代码(在方法中: set_contents_from_fileKey类中)放在已定义或分配fp ,我们可以提供更好的帮助。 But, looking at the error AttributeError: 'str' object has no attribute 'tell' , it is quite clear that fp is not a file object. 但是,查看错误AttributeError: 'str' object has no attribute 'tell' ,很明显fp不是文件对象。 It is a string object, hence the error. 它是一个字符串对象,因此是错误。 As you are new to SO, first try to correct the code yourself, then, if you ae still not getting it resolved, you can paste the code you are using to change fp to a file object. 由于您是SO的新手,首先尝试自己更正代码,然后,如果您仍未解决问题,则可以粘贴用于将fp更改为文件对象的代码。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM