Flask Wtforms的FileField对象没有read属性

1 投票
2 回答
2640 浏览
提问于 2025-04-17 21:52

我正在尝试从一个Flask应用程序上传图片到Amazon S3的存储桶。以下是我的代码:

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)

但是在执行 k.set_contents_from_string(image.read()) 时,我遇到了一个错误,提示 'FileField' object has no attribute 'read'。我查阅的资料都表明这是上传图片到S3的正确方法,而且我也看到过几个例子,它们在 FileField 对象上调用 .read() 时都能正常工作。感谢你的帮助。

2 个回答

0

这样怎么样

import os

filestream = form.image.raw_data[0]
filestream.seek(0, os.SEEK_END)
read_data = filestream.tell()

或者

read_data = form.image.raw_data[0].read()
1

FileField 对象有一个叫做 data 的属性:

k.set_contents_from_string(image.data.read())

撰写回答