Flask 上传图片到 S3 只发送 HTML

1 投票
1 回答
849 浏览
提问于 2025-04-17 21:51

我正在尝试创建一个小应用程序,用来将图片上传到亚马逊的S3存储桶。最终我成功上传了一些东西,但是当我在S3控制台查看时,发现上传的内容竟然是HTML代码:

<input id="image" name="image" type="file">

这是我用Flask写的代码:

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'对象没有'tell'属性

不过我觉得这可能就是问题所在。谢谢你的帮助。

1 个回答

1

只有HTML文件上传成功,是因为你使用了 set_contents_from_string 这个方法。这个方法只适合处理文本文件,而不适合处理图片,因为图片不是以字符串的形式存在。你应该使用 set_contents_from_file 这个方法,具体可以参考文档中的说明

你需要通过 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

撰写回答