【发布时间】:2018-03-03 06:43:44
【问题描述】:
如果您对Python Flask、Boto3、Pillow(又名PIL)有一定的经验,这个问题可能相当简单。
我正在尝试接收来自客户端的传入图像(仅允许 .jpg、.jpeg、.tif,)并且我想在使用将图像上传到 Amazon S3 之前读取图像的尺寸Boto3.
代码相当简单:
file = request.files['file']
# produces an instance of FileStorage
asset = models.Asset(file, AssetType.profile_img, donor.id)
# a model managed by the ORM
img = Image.open(BytesIO(file.stream.read()))
# produces a PIL Image object
size = img.size
# read the size of the Image object
asset.width = size[0]
asset.height = size[1]
# set the size to the ORM
response = s3.Object('my-bucket', asset.s3_key()).put(Body=file)
# upload to S3
这是关键,我可以 (A) 读取图像或 (B) 上传到 s3,但我不能两者都做。从字面上看,注释掉一个或另一个会产生所需的操作,但不能同时使用两者。
我已将范围缩小到上传。我相信在某个地方,file.strea.read() 操作导致 Boto3 上传出现问题,但我无法弄清楚。可以吗?
提前致谢。
【问题讨论】:
-
您可能已经到了直播的末尾。一旦发生这种情况,从 boto 的角度来看,就没有更多的字节可以发送了。如果文件可以放入内存,您可能想尝试 BytesIO 作为中介 - 它可以让您重置流指针,以便您可以在检查后上传。 docs.python.org/3/library/io.html#binary-i-o
-
@killthrush 很好的建议,这也是我的主要假设。我该如何解决?
标签: python python-3.x amazon-web-services amazon-s3 python-imaging-library