【问题标题】:Flask image upload to S3 only sends HTMLFlask 图像上传到 S3 只发送 HTML
【发布时间】:2014-04-15 18:56:58
【问题描述】:

我正在尝试创建一个将图像上传到 Amazon S3 存储桶的小应用程序。我终于能够成功上传 something 但是当我在 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'

但是我觉得这可能是问题所在。感谢您的帮助。

【问题讨论】:

  • 你能发布完整的回溯吗?
  • 没有返回错误,它似乎可以工作,但它只是将该 HTML 上传到文本文件,没有图像。

标签: python amazon-web-services amazon-s3 flask


【解决方案1】:

只有 HTML 上传成功,因为您使用的是 set_contents_from_string 方法,该方法仅适用于基于文本的文件和 not 图像,因为它们不被视为字符串。您应该使用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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-09-23
    • 1970-01-01
    • 1970-01-01
    • 2023-01-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多