瓶图片上传到S3只发送HTML [英] Flask image upload to S3 only sends HTML
问题描述
我想创建一个小的应用程序,上传图像到Amazon S3的桶中。我终于能成功上传的的东西的但是当我在S3控制台检查它所有的上传是HTML:
I'm trying to create a small app that uploads images to an Amazon S3 bucket. I was finally able to successfully upload something however when I checked it in the S3 console all that was uploaded was HTML:
<输入ID =形象NAME =图像类型=文件>
瓶:
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)
我是previously告知,使用 set_contents_from_file
是不正确的,而是使用 set_contents_from_string
I was previously told that using set_contents_from_file
was incorrect and instead to use set_contents_from_string
<一个href="http://stackoverflow.com/questions/22336955/flask-attributeerror-uni$c$c-object-has-no-attribute-tell/22337402#22337402">Flask AttributeError的:UNI code'对象有没有属性'告诉'
不过,我觉得这可能是问题。感谢您的帮助。
However I feel like this may be the issue. Thanks for your help.
推荐答案
只有HTML上传成功,因为你使用 set_contents_from_string
方法,该方法仅适用于基于文本的文件和作品< STRONG>不是图片,因为他们不被视为字符串。您应该使用 set_contents_from_file
方法的在文档中提到这里。
Only HTML uploads were successful because you are using set_contents_from_string
method which works only for text based files and not images since they are not treated as string. You should use set_contents_from_file
method as mentioned in the docs here.
检索文件对象为 request.files ['形象']
,并把它传递给了 set_contents_from_file
方法
Retrieve the file object as request.files['image']
and pass it on to the set_contents_from_file
method.
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
这篇关于瓶图片上传到S3只发送HTML的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!