Forums

500 Internal Server Error (trying to upload file)

Hi, I'm completely new to web application development. I followed the Flask tutorial for uploading files (http://flask.pocoo.org/docs/patterns/fileuploads/). I copied the code exactly except for changing the UPLOAD_FOLDER path. When I try uploading a file I get 500 error. Am I writing the path wrong or is something else wrong? Thank you.


import os
from flask import Flask, request, redirect, url_for
from werkzeug import secure_filename

UPLOAD_FOLDER = '/home/jwebapp3/mysite'
ALLOWED_EXTENSIONS = set(['txt', 'pdf', 'png', 'jpg', 'jpeg', 'gif'])

app = Flask(__name__)
 app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER

def allowed_file(filename):
    return '.' in filename and \
           filename.rsplit('.', 1)[1] in ALLOWED_EXTENSIONS

@app.route('/', methods=['GET', 'POST'])
def upload_file():
    if request.method == 'POST':
        file = request.files['file']
        if file and allowed_file(file.filename):
            filename = secure_filename(file.filename)
            file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename))
            return redirect(url_for('uploaded_file',
                                    filename=filename))
    return '''
    <!doctype html>
    <title>Upload new File</title>
    <h1>Upload new File</h1>
    <form action="" method=post enctype=multipart/form-data>
      <p><input type=file name=file>
         <input type=submit value=Upload>
    </form>
    '''

**EDIT I just noticed that the files are being uploaded properly to the server but for some reason it still gives an error.

Well, the upload itself looks fine, and then the result of the POST operation is a redirect to another URL (which is standard practice for POSTs, to avoid issues reloading the subsequent page and getting browser warnings about resubmitting forms). However, the target of the redirect is url_for('uploaded_file') and I can't see an uploaded_file endpoint in your script - do you mean url_for('upload_file')?

Oops. That's what I meant. Thanks!

Hi jwebapp3, have you checked your error logs? They'll usually tell you what exception your application is raising when you are uploading a file.

Not sure if you ever fixed this but I think your issues is you're missing an uploads folder. It should be this...

UPLOAD_FOLDER = '/home/jwebapp3/mysite/uploads/'

Hope that helps