tarcano tarcano - 1 year ago 73
HTML Question

Internal server error code 500 when uploading a file to a directory with Flask

Here is the backend Flask code for a basic file uploading form

def gallery():

error = None
if request.method == "POST":
if 'file' not in request.files:
flash("No file part")
return redirect(request.url)

file = request.files['file']
print file
file.save(os.path.join(app.config['UPLOAD_FOLDER'], file.filename))
flash('file uploaded successfully')

return render_template('gallery.html')

And the HTML frontend code for the form:

<div class="page">

<p>Upload image</p>
<form action="{{ url_for('gallery') }}" method="post" enctype="multipart/form-data">
<input type="file" name="file"><input type="submit">


I have the UPLOAD_FOLDER variable set to an /uploads directory on the root of my project in which I would like to Flask to store images, however every time I submit an image to upload I get a 500 error.

Strangely enough, if I upload the file to the root of my project directory instead I do not get an error. The error only occurs if I upload the file to my upload directory.

[Edit] Added traceback

Traceback (most recent call last):
File "/Library/Python/2.7/site-packages/flask/app.py", line 1836, in __call__
return self.wsgi_app(environ, start_response)
File "/Library/Python/2.7/site-packages/flask/app.py", line 1820, in wsgi_app
response = self.make_response(self.handle_exception(e))
File "/Library/Python/2.7/site-packages/flask/app.py", line 1403, in handle_exception
reraise(exc_type, exc_value, tb)
File "/Library/Python/2.7/site-packages/flask/app.py", line 1817, in wsgi_app
response = self.full_dispatch_request()
File "/Library/Python/2.7/sitea-packages/flask/app.py", line 1477, in full_dispatch_request
rv = self.handle_user_exception(e)
File "/Library/Python/2.7/site-packages/flask/app.py", line 1381, in handle_user_exception
reraise(exc_type, exc_value, tb)
File "/Library/Python/2.7/site-packages/flask/app.py", line 1475, in full_dispatch_request
rv = self.dispatch_request()
File "/Library/Python/2.7/site-packages/flask/app.py", line 1461, in dispatch_request
return self.view_functions[rule.endpoint](**req.view_args)
File "/Users/fred/personalsite/cool_site.py", line 70, in gallery
file.save(os.path.join(app.config['UPLOAD_FOLDER'], file.filename))
File "/Library/Python/2.7/site-packages/werkzeug/datastructures.py", line 2653, in save
dst = open(dst, 'wb')
IOError: [Errno 2] No such file or directory: u'/uploads/Lecture 1.pages'

Answer Source

What your error says is that the folder does not exist. Create the folder /uploads/ and make it readable for the program. If the folder should be relative to your Flask directory use uploads/ instead.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download