Upload image in Flask
Asked Answered
F

6

47

I have to upload some images in static folder of my project directory, but i don't know how to say it to my code. In the follow code.py i'm able to upload an image and store it in the project directory at the same level of static folder, but i would that this image can be store INSIDE static folder.

@app.route('/uploader', methods = ['GET', 'POST'])
def upload_file():
   if request.method == 'POST':
      f = request.files['file']

      f.save(secure_filename(f.filename))
      return render_template('end.html')

What i have to do?? Thanks guys

Footer answered 5/7, 2017 at 12:36 Comment(1)
It would be nice if you could accept an answer as a correct answerCheerless
D
59

you need to define the upload folder

from the flask documentation

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

UPLOAD_FOLDER = '/path/to/the/uploads'
ALLOWED_EXTENSIONS = set(['txt', 'pdf', 'png', 'jpg', 'jpeg', 'gif'])

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

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))

https://flask.palletsprojects.com/en/1.1.x/patterns/fileuploads/

So your code would be UPLOAD_FOLDER = '/path/to/static/images' or something like that

Docker answered 5/7, 2017 at 12:40 Comment(5)
This and the link were hugely helpful to get an implementation working. ThanksHose
This will work only if you want to upload just one image. If the user select 2 or more images, only the first file will be uploaded. How can be possible upload more than 2 images at the same time?Gentle
@FrancoGil pass a couple files over to flask through javascript/html then loop through them with a for loop. If I recall correctly, you can specify allowing multiple files hence the loopReseau
Thanks @DavidFrick, I forget to estabilsh that I found a solution to this tinny issue.Gentle
def allowed_file(filename): return '.' in filename and filename.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONSAlveolus
S
16
  1. your form's enctype should be multipart/form-data (otherwise it does not work):
<form method="post" enctype="multipart/form-data">
...
</form>
  1. You should specify upload folder (otherwise it does not work):

app.config['UPLOAD_FOLDER'] = '/path/to/the/uploads'

  1. You should specify a name for your file input (otherwise it does not work):
<input type="file" name="file1">
  1. you should manually save the file with file save() method:
path = os.path.join(app.config['UPLOAD_FOLDER'], file1.filename)
file1.save(path)
  1. Simple full example:
import os
from flask import Flask, request

UPLOAD_FOLDER = './upload'

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

@app.route('/', methods=['GET', 'POST'])
def upload_file():
    if request.method == 'POST':
        if 'file1' not in request.files:
            return 'there is no file1 in form!'
        file1 = request.files['file1']
        path = os.path.join(app.config['UPLOAD_FOLDER'], file1.filename)
        file1.save(path)
        return path

        return 'ok'
    return '''
    <h1>Upload new File</h1>
    <form method="post" enctype="multipart/form-data">
      <input type="file" name="file1">
      <input type="submit">
    </form>
    '''

if __name__ == '__main__':
    app.run()
  1. Detailed full example: https://flask.palletsprojects.com/en/1.1.x/patterns/fileuploads/
Slangy answered 6/6, 2020 at 11:56 Comment(0)
V
3

Add enctype="multipart/form-data" to form that contains your input type=file After that,

from os.path import join, dirname, realpath
from werkzeug.utils import secure_filename

UPLOADS_PATH = join(dirname(realpath(__file__)), 'static\\img')

        

if request.files['image'].filename != '':
                image = request.files['image']
                image.save(os.path.join(UPLOADS_PATH, secure_filename(image.filename)))
Vinegar answered 21/8, 2020 at 16:19 Comment(0)
Q
2

Try to first store the image jpeg or jpg in a static folder enter image description here enter image description here inside the static folder the image is stored
enter image description here

then in the html file

<img src="{{url_for('static', filename='Hermes.png')}}" align="middle" />

add this code line

In app.py the code

from flask import Flask, render_template, redirect, url_for, request


# Route for handling the login page logic
app = Flask(__name__)


@app.route('/', methods=['GET', 'POST'])
def home():
    return render_template('home.html')

@app.route('/register')
def register():
    return render_template('register.html')

@app.route('/registerV')
def registerV():
    return render_template('registerV.html')

In register.html the code

<html>
    <head>
    </head>

    <body>
    <div class="bd-example" align="middle">
            <img src="{{url_for('static', filename='Hermes.png')}}" align="middle" />
            </div>
    </body>
</html>
Quintanilla answered 4/10, 2019 at 8:39 Comment(0)
M
1

For some reason, @PYA 's code won't work for me, but I made a small change:
I used 'path/to/the/uploads' instead of '/path/to/the/uploads' and everything works fine.

Mercola answered 8/11, 2019 at 19:22 Comment(0)
T
0

Don't need "/" for folders in project's folder:

UPLOAD_FOLDER = 'static/images'
Thorsten answered 9/4, 2023 at 10:37 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.