Upload image in Flask

落爺英雄遲暮 提交于 2019-11-26 16:42:42

问题


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


回答1:


you need to define the upload folder

from the flask documentation

import os
from flask import Flask, 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




回答2:


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

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>



回答3:


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.



来源:https://stackoverflow.com/questions/44926465/upload-image-in-flask

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!