Home > Enterprise >  Flask Uploading Files Tutorial returns 404
Flask Uploading Files Tutorial returns 404

Time:07-08

I am following this tutorial on creating file uploads in Flask. https://flask.palletsprojects.com/en/2.0.x/patterns/fileuploads/

My file structure is as follows

flask
     -index.py
     uploads
          -<filename>

The code in index.py is as follows, an exact copy and paste from the tutorial

import os
from flask import Flask, request, redirect, url_for, flash
from werkzeug.utils import secure_filename

UPLOAD_FOLDER = 'flask/uploads'
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].lower() in ALLOWED_EXTENSIONS

@app.route('/', methods=['GET', 'POST'])
def upload_file():
    if request.method == 'POST':
        # check if the post request has the file part
        if 'file' not in request.files:
            flash('No file part')
            return redirect(request.url)
        file = request.files['file']
        # if user does not select file, browser also
        # submit a empty part without filename
        if file.filename == '':
            flash('No selected file')
            return redirect(request.url)
        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 method=post enctype=multipart/form-data>
      <p><input type=file name=file>
         <input type=submit value=Upload>
    </form>
    '''

from flask import send_from_directory

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


if __name__ == '__main__':
   app.run(port=8000)

My issue is this, when I upload a file, I get a 404 trying to access the @app.route('/uploads/') view. See log below. Ive look at many stack overflow answers but have yet to fix the issue.

27.0.0.1 - - [07/Jul/2022 12:59:44] "GET / HTTP/1.1" 200 -
127.0.0.1 - - [07/Jul/2022 12:59:44] "GET /favicon.ico HTTP/1.1" 404 -
127.0.0.1 - - [07/Jul/2022 12:59:48] "POST / HTTP/1.1" 302 -
127.0.0.1 - - [07/Jul/2022 12:59:48] "GET /uploads/Figure_1.png HTTP/1.1" 404 -

CodePudding user response:

change this: UPLOAD_FOLDER = 'flask/uploads' to this: UPLOAD_FOLDER = 'uploads'

your .py file and upload folder are at the same directory level.

CodePudding user response:

You need to do two things:

  1. Create an uploads directory in the same directory as your flask index.py
  2. Update the line UPLOAD_FOLDER = 'flask/uploads' to UPLOAD_FOLDER = 'uploads'

Then it works a treat!

Revised code looks like this:

import os
from flask import Flask, request, redirect, url_for, flash
from werkzeug.utils import secure_filename

UPLOAD_FOLDER = 'uploads'
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].lower() in ALLOWED_EXTENSIONS

@app.route('/', methods=['GET', 'POST'])
def upload_file():
    if request.method == 'POST':
        # check if the post request has the file part
        if 'file' not in request.files:
            flash('No file part')
            return redirect(request.url)
        file = request.files['file']
        # if user does not select file, browser also
        # submit a empty part without filename
        if file.filename == '':
            flash('No selected file')
            return redirect(request.url)
        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 method=post enctype=multipart/form-data>
      <p><input type=file name=file>
         <input type=submit value=Upload>
    </form>
    '''

from flask import send_from_directory

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


if __name__ == '__main__':
   app.run(port=8000)

Folder structure:

-Flask
   -index.py
   -uploads
       -theuploadedfile.pdf
  • Related