Commit 96f5375c authored by Phil Schleihauf's avatar Phil Schleihauf

Update filename on werkzeug FileStorage for uploaded files

This is an issue for fields whose name might be changed at any point, like any image ending in "jpeg" (which will be renamed to "jpg". That would cause the actual file to be saved to disk with ".jpeg", but be saved elsewhere as ".jpg".

This example (mostly copied from the example in `examples/forms/simple.py`) shows it better than I can explain:

    import os
    from flask import Flask
    from flask.ext.admin import Admin, form
    from flask.ext.admin.contrib import sqla
    from flask.ext.sqlalchemy import SQLAlchemy

    app = Flask(__name__)
    app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///hello.db'
    db = SQLAlchemy(app)

    os.path.isdir('static') or os.mkdir('static')

    class Photo(db.Model):
        id = db.Column(db.Integer, primary_key=True)
        path = db.Column(db.Unicode(128))

    class PhotoView(sqla.ModelView):
        form_extra_fields = {'path': form.ImageUploadField('Photo', base_path='static')}

    admin = Admin(app, 'Photos are broken!')
    admin.add_view(PhotoView(Photo, db.session))

    db.create_all()
    app.run(debug=True)

... try uploading files with `.jpeg` vs `.jpg` extensions. It's pretty broken.
parent 805279fb
......@@ -208,6 +208,8 @@ class FileUploadField(fields.TextField):
filename = self.generate_name(obj, self.data)
filename = self._save_file(self.data, filename)
# update filename of FileStorage to our validated name
self.data.filename = filename
setattr(obj, name, filename)
......
......@@ -95,6 +95,10 @@ def test_image_upload_field():
safe_delete(path, 'test2.png')
safe_delete(path, 'test2_thumb.jpg')
safe_delete(path, 'test1.jpg')
safe_delete(path, 'test1.jpeg')
safe_delete(path, 'test1.gif')
safe_delete(path, 'test1.png')
safe_delete(path, 'test1.tiff')
class TestForm(form.BaseForm):
upload = form.ImageUploadField('Upload',
......@@ -204,6 +208,19 @@ def test_image_upload_field():
ok_(op.exists(op.join(path, 'test1.jpg')))
# check allowed extensions
for extension in ('gif', 'jpg', 'jpeg', 'png', 'tiff'):
filename = 'copyleft.' + extension
filepath = op.join(op.dirname(__file__), 'data', filename)
with open(filepath, 'rb') as fp:
with app.test_request_context(method='POST', data={'upload': (fp, filename)}):
my_form = TestNoResizeForm(helpers.get_form_data())
ok_(my_form.validate())
my_form.populate_obj(dummy)
eq_(dummy.upload, my_form.upload.data.filename)
def test_relative_path():
app = Flask(__name__)
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment