如何将上传的文件传递到亚马逊s3?

时间:2015-01-06 20:08:49

标签: amazon-s3 flask

我的代码中有这个:

size=128,128
@app.route('/',methods=['GET','POST'])
def upload():
        print request.method
        if request.method == 'POST':
                file = request.files['image']
                im = Image.open(file)
                im.resize(size)
                im.save("test.png","PNG")
                f=open("test.png",'r')
                conn = tinys3.Connection('AKIAI2GPQ','fAQxDLbvZcqhXvjd',tls=True)    
                conn.upload(im,f,"snappie.watermarks")
                print "got file"
                return redirect("https://www.google.com")
         return render_template('index.html')

希望您可以看到我正在尝试处理来自request.files的文件上传,调整大小,然后将其上传到amazon s3。但是现在它被挂在了conn.upload(im,f,"snappie.watermarks")线上。

这是错误:

File "/home/alex/snappie/web/server.py", line 25, in upload
conn.upload(im,f,"snappie.watermarks")
File "/usr/local/lib/python2.7/dist-packages/tinys3/connection.py", line 152, in upload
return self.run(r)
File "/usr/local/lib/python2.7/dist-packages/tinys3/connection.py", line 233, in run
return self._handle_request(request)
File "/usr/local/lib/python2.7/dist-packages/tinys3/connection.py", line 255, in _handle_request
return request.run()
File "/usr/local/lib/python2.7/dist-packages/tinys3/request_factory.py", line 147, in run
headers['Content-Type'] = self.content_type or mimetypes.guess_type(self.key)[0] or 'application/octet-stream'
File "/usr/lib/python2.7/mimetypes.py", line 298, in guess_type
return _db.guess_type(url, strict)
File "/usr/lib/python2.7/mimetypes.py", line 114, in guess_type
scheme, url = urllib.splittype(url)
File "/usr/lib/python2.7/urllib.py", line 1074, in splittype
match = _typeprog.match(url)
TypeError: expected string or buffer

显然它与这三个论点中的一个有问题,但我不确定是哪一个?我也不确定我是否正确处理文件。我是否需要保存图像然后重新打开才能将其上传到亚马逊s3?我这样做是因为所有的tinys3例子都这样做了,但是我的文件已经打开了所以可能是多余的?

1 个答案:

答案 0 :(得分:0)

看起来您的图片参数可能会混淆。这是我们想要的签名:

conn.upload(key, local_file, bucket)

tinys3 expects a string value for the key和local_file的类似文件的打开对象。请尝试以下方法:

conn.upload("test.png", f, "snappie.watermarks")