I'm trying to upload images to an Amazon S3 bucket from a Flask app. Here is my code:
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.read())
return iid
@app.route('/', methods = ['GET', 'POST'])
def index():
form = ImageForm(request.form)
print 'CHECKING REQUEST'
if request.method == 'POST' and form.image:
print 'VALID REQUEST'
image = form.image.read()
upload = s3upload(image)
print upload
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, image=image)
However I get an error at k.set_contents_from_string(image.read())
saying 'FileField' object has no attribute 'read'
. Everything I've ready has indicated this is the proper way to upload an image to S3 and I've found several examples where they call .read()
on a FileField
object and it works fine. Thanks for your help.
FileField
对象具有data
属性:
k.set_contents_from_string(image.data.read())
How about
import os
filestream = form.image.raw_data[0]
filestream.seek(0, os.SEEK_END)
read_data = filestream.tell()
or
read_data = form.image.raw_data[0].read()
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.