3

I'm using Flask-Uploads to upload a file and output the URL. However, for some reason the URL always points to a 404! I can see the file in the correct folder, but the URL seems to not be able to find it. Here are the configurations I'm using...

UPLOADS_DEFAULT_URL = os.environ.get("UPLOADS_URL", "http://localhost:5000/")
UPLOADS_DEFAULT_DEST = "app/uploads"

I also have an Upload set defined as:

productUploadSet = UploadSet('plist', extensions=('xlsx', 'csv', 'xls'))

The file is found in "app/uploads/plist/filename.csv" and I'll get a url returned to me like "http://localhost:5000/productlist/filename.csv" but whenever I open the URL it is always a 404. I know that the url method from Flask-Uploads doesn't actually check fi the file exists, but I can see the file is actually there. Is it looking in the wrong place somehow? Thanks for any help.

Jeff Widman
  • 22,014
  • 12
  • 72
  • 88
kevin.w.johnson
  • 1,684
  • 3
  • 18
  • 37
  • Can you show us the view you use to return the uploaded files? – dirn Feb 12 '15 at 21:09
  • I don't have a specific view returning the uploaded files. Flask-Uploads generates the URL and returns the uploaded file using Flask's send_from_directory. http://flask.pocoo.org/docs/0.10/patterns/fileuploads/ – kevin.w.johnson Feb 12 '15 at 21:43
  • You have to use `send_from_directory` within a view. – dirn Feb 12 '15 at 21:54

1 Answers1

3

From Flask's guide to uploading files:

Now one last thing is missing: the serving of the uploaded files. As of Flask 0.5 we can use a function that does that for us:

from flask import send_from_directory

@app.route('/uploads/<filename>')
def uploaded_file(filename):
    return send_from_directory(app.config['UPLOAD_FOLDER'],
                               filename)

Alternatively you can register uploaded_file as build_only rule and use the SharedDataMiddleware. This also works with older versions of Flask:

from werkzeug import SharedDataMiddleware
app.add_url_rule('/uploads/<filename>', 'uploaded_file',
                 build_only=True)
app.wsgi_app = SharedDataMiddleware(app.wsgi_app, {
    '/uploads':  app.config['UPLOAD_FOLDER']
})

Without implementing one of these, Flask has no idea how to serve the uploaded files.

dirn
  • 19,454
  • 5
  • 69
  • 74