Skip to content

Instantly share code, notes, and snippets.

@greyli
Last active May 16, 2022 12:58
Show Gist options
  • Star 15 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save greyli/81d7e5ae6c9baf7f6cdfbf64e8a7c037 to your computer and use it in GitHub Desktop.
Save greyli/81d7e5ae6c9baf7f6cdfbf64e8a7c037 to your computer and use it in GitHub Desktop.
Photo upload demo with Flask-Uploads and Flask-WTF.
<!-- create a folder named templates, put this file into it -->
<!DOCTYPE html>
<title>Upload File</title>
<h1>Photo Upload</h1>
<form method="POST" enctype="multipart/form-data">
{{ form.hidden_tag() }}
{{ form.photo }}
{% for error in form.photo.errors %}
<span style="color: red;">{{ error }}</span>
{% endfor %}
{{ form.submit }}
</form>
{% if file_url %}
<br>
<img src="{{ file_url }}">
{% endif %}
# -*- coding: utf-8 -*-
import os
from flask import Flask, render_template
from flask_uploads import UploadSet, configure_uploads, IMAGES, patch_request_class
from flask_wtf import FlaskForm
from flask_wtf.file import FileField, FileRequired, FileAllowed
from wtforms import SubmitField
basedir = os.path.abspath(os.path.dirname(__file__))
app = Flask(__name__)
app.config['SECRET_KEY'] = 'I have a dream'
app.config['UPLOADED_PHOTOS_DEST'] = os.path.join(basedir, 'uploads') # you'll need to create a folder named uploads
photos = UploadSet('photos', IMAGES)
configure_uploads(app, photos)
patch_request_class(app) # set maximum file size, default is 16MB
class UploadForm(FlaskForm):
photo = FileField(validators=[FileAllowed(photos, 'Image only!'), FileRequired('File was empty!')])
submit = SubmitField('Upload')
@app.route('/', methods=['GET', 'POST'])
def upload_file():
form = UploadForm()
if form.validate_on_submit():
filename = photos.save(form.photo.data)
file_url = photos.url(filename)
else:
file_url = None
return render_template('index.html', form=form, file_url=file_url)
if __name__ == '__main__':
app.run()
@KUDANDOU
Copy link

KUDANDOU commented Feb 20, 2018

I am getting the below error if i try to compile your code

Internal Server Error

The server encountered an internal error and was unable to complete your request. Either the server is overloaded or there is an error in the application.

@KUDANDOU
Copy link

managed to make it work

@ClaudioReevas
Copy link

ClaudioReevas commented Jun 25, 2018

Hi, I found something interesting. If you copy and paste the image address in your browser after you upload the image you can paste it and see it enabling a different route like http://127.0.0.1:5002/_uploads/photos/picture.png and with this you can point directly to your application file http://127.0.0.1:5002/_uploads/photos/upload.py or any file on the folder.

I have three questions:
Is this the intended use?
is there any way to prevent this?
is this library supported by someone?

I've done the video on spanish but hope it helps https://youtu.be/jv3BH3PW-iE

@HengyueLi
Copy link

HengyueLi commented Jul 20, 2018

This code is not working. One should make a folder named 'templates', which contains the 'index.html'. After that, it works. @KUDANDOU
Anyway, this is a good example.

@batyrata
Copy link

This code works but as @ClaudioReevas said it creates this "virtual folder" called _uploads which is not visible at all in my project. Even though I have created a folder for uploading images and specified it in my settings.py it doesn't see that path at all. Is there any way to fix it?

@HengyueLi
Copy link

Now I am also confused with this problem. According to my understanding "app.config['UPLOADED_PHOTOS_DEST']" should be set as a temporary folder, such as "/tmp". For database use, we need to move the data from this folder to another place, where we used to save the data permanently. I am not so sure if this understanding is correct. But anyway, I want to do it like this.

@vonderasche
Copy link

this helped me out a lot thank you

@vegarsti
Copy link

Thank you so much!

@corei8
Copy link

corei8 commented Jul 21, 2019

app.config['UPLOADED_PHOTOS_DEST'] = os.getcwd() + '/app/tmp/'

The above change will send the photo to a directory other than the current directory.

Thank you very much for the code!

@StarORC
Copy link

StarORC commented Mar 15, 2020

请问,用Flask_uploads做了一个上传手机照片的页面,但偶尔还是会有

    raise UploadNotAllowed()
flask_uploads.UploadNotAllowed

想用try/except查找此情况下上传文件的扩展名。
但是:
except UploadNotAllowed as error:
会报错:
NameError: name 'UploadNotAllowed' is not defined
还试过flask_uploads.UploadNotAllowedflask_uploads,但都说没定义。
请问这里该怎么写?感谢~

I using Flask_uploads to make a page to upload mobile photos,
but occasionally there still be

    raise UploadNotAllowed()
flask_uploads.UploadNotAllowed

I want to use try / except to find the extension of the uploaded file.
but:
except UploadNotAllowed as error:
Will report an error:
NameError: name 'UploadNotAllowed' is not defined
I also tried flask_uploads.UploadNotAllowed or flask_uploads, but they all undefined.
What should I write here? thank~

@StarORC
Copy link

StarORC commented Mar 15, 2020

请问,用Flask_uploads做了一个上传手机照片的页面,但偶尔还是会有

    raise UploadNotAllowed()
flask_uploads.UploadNotAllowed

想用try/except查找此情况下上传文件的扩展名。
但是:
except UploadNotAllowed as error:
会报错:
NameError: name 'UploadNotAllowed' is not defined
还试过flask_uploads.UploadNotAllowedflask_uploads,但都说没定义。
请问这里该怎么写?感谢~

I using Flask_uploads to make a page to upload mobile photos,
but occasionally there still be

    raise UploadNotAllowed()
flask_uploads.UploadNotAllowed

I want to use try / except to find the extension of the uploaded file.
but:
except UploadNotAllowed as error:
Will report an error:
NameError: name 'UploadNotAllowed' is not defined
I also tried flask_uploads.UploadNotAllowed or flask_uploads, but they all undefined.
What should I write here? thank~

ok,i konw,need from flask_uploads import UploadNotAllowed

@masouduut94
Copy link

Does IMAGES support video format too?
@StarORC

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment