我正在尝试创建一个将图像上传到Amazon S3存储桶的小应用。我终于能够成功上传某些东西然而当我在S3控制台中检查时,所有上传的内容都是HTML:
<input id="image" name="image" type="file">
烧瓶中:
def s3upload(image, acl='public-read'):
key = app.config['S3_KEY']
secret = app.config['S3_SECRET']
bucket = app.config['S3_BUCKET']
conn = S3Connection(key, secret)
mybucket = conn.get_bucket(bucket)
r = redis.StrictRedis(connection_pool = pool)
iid = r.incr('image')
now = time.time()
r.zadd('image:created_on', now, iid)
k = Key(mybucket)
k.key = iid
k.set_contents_from_string(image)
return iid
@app.route('/', methods = ['GET', 'POST'])
def index():
form = ImageForm(request.form)
print 'CHECKING REQUEST'
if form.validate_on_submit():
print 'VALID REQUEST'
image = form.image.data
s3upload(image)
else:
image = None
r = redis.StrictRedis(connection_pool = pool)
last_ten = r.zrange('image:created_on', 0, 9)
print last_ten
images = []
key = app.config['S3_KEY']
secret = app.config['S3_SECRET']
bucket = app.config['S3_BUCKET']
conn = S3Connection(key, secret)
mybucket = conn.get_bucket(bucket)
for image in last_ten:
images.append(mybucket.get_key(image, validate = False))
return render_template('index.html', form=form, images=images)
我之前被告知使用set_contents_from_file
不正确,而是使用set_contents_from_string
Flask AttributeError: 'unicode' object has no attribute 'tell'
但我觉得这可能是个问题。谢谢你的帮助。
答案 0 :(得分:1)
只有HTML上传成功,因为您使用的set_contents_from_string
方法仅适用于基于文本的文件和非图像,因为它们不会被视为字符串。您应该将set_contents_from_file
方法用作mentioned in the docs here。
将文件对象检索为request.files['image']
并将其传递给set_contents_from_file
方法。
def s3upload(image, acl='public-read'):
# do things before
k.set_contents_from_file(image)
# do more stuff
@app.route('/', methods = ['GET', 'POST'])
def index():
form = ImageForm(request.form)
if form.validate_on_submit():
s3upload(request.files['image'])
# do rest of stuff