I'm new to Flask. I wanted to create a very basic site which allows to upload the images.I found the manual, however I wanted to make it slightly different. Here's my code:
###main.py
import os
from forms import UploadForm
from flask import Flask,render_template, url_for, redirect, send_from_directory
from werkzeug import secure_filename
ALLOWED_EXTENSIONS = set(['txt', 'pdf', 'png', 'jpg', 'jpeg', 'gif'])
def allowed_file(filename):
    return '.' in filename and \
           filename.rsplit('.', 1)[1] in ALLOWED_EXTENSIONS
app = Flask(__name__)
app.config['SECRET_KEY'] = 'string'
@app.route('/', methods=('GET', 'POST'))
def upload():
    form = UploadForm()
    if form.validate_on_submit() and allowed_file(form.presentation.File.filename):
        filename = secure_filename(form.presentation.file.filename)
        print filename
        form.presentation.File.save(os.path.join('C:\Users\user\Desktop\New', filename))
    return redirect(url_for('/'))
    filename = None
    return render_template('upload.html', form=form, filename=filename)
if __name__ == '__main__':
    app.run(debug=True)
### forms.py   
from flask.ext.wtf import Form
from wtforms import FileField, validators, ValidationError, SubmitField
from wtforms.validators import InputRequired
class UploadForm(Form):
  presentation = FileField('Upload Image here', validators=[InputRequired()])
  submit = SubmitField("Send")
### upload.html
   {% for message in form.presentation.errors %}
     <div class="flash">{{ message }}</div>
   {% endfor %}
   <form action="/" method="POST" enctype="multipart/form-data">
     {{ form.presentation.label }}
     {{ form.presentation }}
     {{ form.csrf_token }}
     {{ form.submit}}
   </form>
On executing I get an error: AttributeError: 'FileField' object has no attribute 'File' I've searched the whole day, but I cannot find the answer what's wrong.
According to the wtforms doc FileField does not have File attribute that's right.
Here is the doc example:
class UploadForm(Form):
    image        = FileField(u'Image File', [validators.regexp(u'^[^/\\]\.jpg$')])
    description  = TextAreaField(u'Image Description')
    def validate_image(form, field):
        if field.data:
            field.data = re.sub(r'[^a-z0-9_.-]', '_', field.data)
def upload(request):
    form = UploadForm(request.POST)
    if form.image.data:
        image_data = request.FILES[form.image.name].read()
        open(os.path.join(UPLOAD_PATH, form.image.data), 'w').write(image_data)
As you can see the file is read from request.FILE not from the FileField. The FileField only has the attributes name and data.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With