python 在Flask中上传图像

u0njafvf  于 2023-04-10  发布在  Python
关注(0)|答案(6)|浏览(139)

我不得不上传一些图像在我的项目目录的静态文件夹,但我不知道如何说我的代码.在下面的code.py我能够上传一个图像,并将其存储在项目目录中的同一级别的静态文件夹,但我希望这张图片可以存储在内部静态文件夹.

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

我该怎么做??谢谢你们

thtygnil

thtygnil1#

您需要定义upload folder
来自flask文档

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/
所以你的代码应该是UPLOAD_FOLDER = '/path/to/static/images'或者类似的东西

dced5bon

dced5bon2#

1.您的表单的enctype应该是multipart/form-data(否则它不工作):

<form method="post" enctype="multipart/form-data">
...
</form>

1.您应该指定上传文件夹(否则它不起作用):
app.config['UPLOAD_FOLDER'] = '/path/to/the/uploads'
1.您应该为文件输入指定一个名称(否则将无法工作):

<input type="file" name="file1">

1.你应该手动保存文件与文件save()方法:

path = os.path.join(app.config['UPLOAD_FOLDER'], file1.filename)
file1.save(path)

1.简单完整的示例:

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.详细完整示例:https://flask.palletsprojects.com/en/1.1.x/patterns/fileuploads/

pieyvz9o

pieyvz9o3#

enctype="multipart/form-data"添加到包含您的input type=file的表单中之后,

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

ru9i0ody4#

尝试先将图像jpeg或jpg存储在静态文件夹


中,该文件夹位于存储图像的静态文件夹内

然后在html文件中

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

添加此代码行
在www.example.com中app.py,代码

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

在register.html中的代码

<html>
    <head>
    </head>

    <body>
    <div class="bd-example" align="middle">
            <img src="{{url_for('static', filename='Hermes.png')}}" align="middle" />
            </div>
    </body>
</html>
vpfxa7rd

vpfxa7rd5#

出于某种原因,@PYA的代码对我不起作用,但我做了一个小改动:
我使用了'path/to/the/uploads'而不是'/path/to/the/uploads',一切正常。

8qgya5xd

8qgya5xd6#

项目文件夹中的文件夹不需要“/”:

UPLOAD_FOLDER = 'static/images'

相关问题