如何通过Flask上传图片?

时间:2016-04-19 09:47:39

标签: python flask

我想使用Flask构建一个库,我所做的就是构建一个Model和一个View,一个简单的html来上传文件。

class Image(db.Model):
    __tablename__ = 'images'
    id = db.Column(db.Integer, primary_key=True)
    url = db.Column(db.String)

    timestamp = db.Column(db.DateTime, index=True,default=datetime.utcnow)
    author_id = db.Column(db.Integer, db.ForeignKey('users.id'))

    def get_image(self):
       return send_from_directory(self.url, '')

我的观点如下:

@gallery.route('/', methods=['GET', 'POST'])
@gallery.route('/index', methods=['GET', 'POST'])
def index():
    page = request.args.get('page', 1, type=int)
    pagination = Image.query.order_by(Image.timestamp.desc()).paginate(
        page, per_page=current_app.config['LANDPACK_POSTS_PER_PAGE'],
        error_out=False
)
    posts = pagination.items
    return render_template('gallery/index.html', posts=posts, pagination=pagination)
@gallery.route('/upload', methods=['GET', 'POST'])
def upload():
    form = ImageForm()
    if request.method == 'POST':
        filename = secure_filename(form.image.data.filename)
        image_url = os.path.join(current_app.config['UPLOAD_FOLDER'], filename)
        form.image.data.save(image_url)
        image = Image(url=image_url)
        db.session.add(image)
        db.session.commit()
        flash('You have add a new photo!')
        send_file = send_from_directory(image_url, filename)
        print send_file
        return redirect(url_for('.index'))
    else:
        filename = None

    return render_template('gallery/upload.html', form=form)

我的表格:

from flask.ext.wtf import Form
from flask.ext.wtf import Form
from wtforms import StringField, PasswordField, BooleanField,  SubmitField, IntegerField
from wtforms.validators import Required, Email, Length, Regexp, EqualTo
from wtforms import ValidationError
from flask_wtf.file import FileField


class ImageForm(Form):
    name = StringField('Image Name', validators=[Length(1, 64)])
    tag = IntegerField('Tag Value', default=50, validators=[Required(), Length(1, 64)])
    image = FileField('Your photo')
    submit = SubmitField('Upload Image')

简而言之,我只是在这里粘贴上传表单的核心。

<img class="img-rounded profile-thumbnail" src="{{ post.get_image() }}">

那么,如何在将图像上传到服务器后获取网址?如下:

  

http://127.0.0.1/image/sample.jpg

2 个答案:

答案 0 :(得分:3)

@lapinkoira的回答是正确的。除此之外,您还可以使用以下代码检查index()函数内部,是否存在文件:

if request.files:    
    filename = request.files['file']
    print filename

答案 1 :(得分:2)

这是send_from_directory的文档:

  

flask.send_from_directory(目录,文件名,**选项)

您在示例中没有发送文件名,只需使用self.url作为目录和空文件名参数。

你应该有这样的东西:

send_from_directory(app.config['UPLOAD_FOLDER'],
                    filename)

可在此处找到更多信息: http://flask.pocoo.org/docs/0.10/api/#flask.send_from_directory