简体   繁体   中英

How to upload image by Flask?

I want to build a gallery by use Flask, and what I had done is build a Model and A View , a simple html to upload file.

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, '')

And My view is below:

@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)

My 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')

To short, I just paste the core of upload form here.

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

So, How can I fetch a url after upload a image to the server? as following:

http://127.0.0.1/image/sample.jpg )

The answer by @lapinkoira is correct. In addition to this, You can also check inside the index() function using the below code, whether there is a file exist or not:

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

This is the documentation for send_from_directory:

flask.send_from_directory(directory, filename, **options)

You are not sending a filenamem in your example you just use self.url as directory and empty filename parameter.

You should have something like this:

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

More information can be found here: http://flask.pocoo.org/docs/0.10/api/#flask.send_from_directory

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM