Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Flask-Uploads IOError: [Errno 2] No such file or directory

So, I've been trying to add an image uploader to my code, but I've been running into issues. Even though I thought I had my upload_folder configured properly, I keep getting errors like: IOError: [Errno 2] No such file or directory: '/static/uploads/compressor.jpg' even though the file/directory exists.

Here's the code:

in config.py

UPLOAD_FOLDER = 'static/uploads'

in init.py

app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER

in views.py

@app.route('/fileupload', 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 an 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>
    <h>UPload new file</h1>
    <form action="" method=post enctype=multipart/form-data>
        <p><input type=file name=file>
            <input type=submit value=Upload>
    </form>
    '''

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

My folder structure is as follows

  /project folder
   --/app
   ----/static
   --------/uploads
   ----/templates
   ----_init__.py
   ----views.py
   --config.py

When I use /tmp/ to store it in memory the uploader works no problem. I assume it's not looking in the proper path for my folder. Can anyone help here? I'm a very amateur python developer.

like image 239
dizzy Avatar asked Jun 18 '16 21:06

dizzy


1 Answers

Both /tmp and /static/uploads/.., are absolute paths. And your code is looking in the / folder instead of looking in your project's folder. You should use the absolute path to point at your folder /path/to/your/project/static/uploads/.. or use a path relative to the code being executed such as ./static/uploads.

You can also use the following snippet to generate the absolute path:

from os.path import join, dirname, realpath

UPLOADS_PATH = join(dirname(realpath(__file__)), 'static/uploads/..')
like image 88
kardaj Avatar answered Oct 29 '22 01:10

kardaj