在这里,我将向您展示如何允许用户上传图像文件并在上传成功后将其显示在浏览器上。
将图片、css、javascript 文件等静态资源存储到 Flask 应用程序中的标准目录是放在 static 目录下。
在这里,我将上传的文件放在 static/files 目录下,最终您将在网页上显示图像。
那么让我们看看下面的例子:
Example
接下来我将创建main.py脚本来配置用于上传文件或图像的端点。它定义了执行文件上传操作所需的 URI。
main.py
from flask import Flask, render_template, session, flash
from flask_wtf import FlaskForm
from wtforms import FileField, SubmitField
from werkzeug.utils import secure_filename
import os
from wtforms.validators import InputRequired
app = Flask(__name__)
app.config['SECRET_KEY'] = 'supersecretkey'
app.config['UPLOAD_FOLDER'] = 'static/files'
class UploadFileForm(FlaskForm):
file = FileField("File", validators=[InputRequired()])
submit = SubmitField("Upload File")
@app.route('/', methods=['GET',"POST"])
@app.route('/home', methods=['GET',"POST"])
def home():
form = UploadFileForm()
if form.validate_on_submit():
file = form.file.data # First grab the file
file.save(os.path.join(os.path.abspath(os.path.dirname(__file__)),app.config['UPLOAD_FOLDER'],secure_filename(file.filename))) # Then save the file
session['name'] = 'Image Upload Successfully'
flash(f"{session['name']}")
return render_template('index.html', form=form)
if __name__ == '__main__':
app.run(debug=True)
创建视图文件Create a View File
在这一步中,现在我们需要用于上传文件的模板页面,它也会显示上传的图像。
这是保存在目录-templates下的index.html页面,这是flask应用程序中存储模板或视图文件的标准目录。
index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@4.6.1/dist/css/bootstrap.min.css">
<script src="https://cdn.jsdelivr.net/npm/jquery@3.6.0/dist/jquery.slim.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/popper.js@1.16.1/dist/umd/popper.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@4.6.1/dist/js/bootstrap.bundle.min.js"></script>
</head>
<body>
<div class="container mt-5 pt-5">
<div class="row d-flex justify-content-center">
<div class="col-md-8">
<div class="card">
<div class="card-header bg-primary text-white">
<h4>Python Image Upload Using Flask Example - Tuts-Station.com</h4>
</div>
<div class="card-body">
{% for mess in get_flashed_messages() %}
<div class="alert alert-success alert-dismissible fade show" role="alert">
<button type="button" class="close" data-dismiss="alert" aria-label="Close" class="fade close">
<span aria-hidden="true">×</span>
</button>
{{mess}}
</div>
{% endfor %}
<form method='POST' enctype='multipart/form-data'>
{{form.hidden_tag()}}
<label>Image:</label>
<div class="custom-file">
<input type="file" class="custom-file-input" id="file" name="file" required>
<label class="custom-file-label" for="file">Choose file</label>
</div>
<div class="col-md-12 mt-3 text-center">
<button type="submit" class="btn btn-success">Submit</button>
</div>
</form>
</div>
</div>
</div>
</div>
</div>
<script>
// Add the following code if you want the name of the file appear on select
$(".custom-file-input").on("change", function() {
var fileName = $(this).val().split("\\").pop();
$(this).siblings(".custom-file-label").addClass("selected").html(fileName);
});
</script>
</body>
</html>
Run Example
python3 main.py
Output:

希望对您有用….
python-image-upload-using-flask-example
