以下是一个简单的 Python Flask 程序,它可以让用户上传图片并将其保存在服务器上。要运行此程序,您需要安装 Flask 和 Pillow 库。

from flask import Flask, render_template, request, redirect, url_for
from werkzeug.utils import secure_filename
from PIL import Image

app = Flask(__name__)
app.config['UPLOAD_FOLDER'] = 'uploads'
app.config['ALLOWED_EXTENSIONS'] = {'png', 'jpg', 'jpeg', 'gif'}

def allowed_file(filename):
    return '.' in filename and \
           filename.rsplit('.', 1)[1].lower() in app.config['ALLOWED_EXTENSIONS']

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

@app.route('/upload', methods=['POST'])
def upload():
    file = request.files['file']
    if file and allowed_file(file.filename):
        filename = secure_filename(file.filename)
        file.save(app.config['UPLOAD_FOLDER'] + '/' + filename)
        img = Image.open(app.config['UPLOAD_FOLDER'] + '/' + filename)
        img.thumbnail((200, 200))
        img.save(app.config['UPLOAD_FOLDER'] + '/' + filename)
        return redirect(url_for('uploaded_file', filename=filename))
    else:
        return redirect(url_for('index'))

@app.route('/uploads/<filename>')
def uploaded_file(filename):
    return render_template('uploaded.html', filename=filename)

if __name__ == '__main__':
    app.run(debug=True)

这个程序的核心是 upload() 函数,它处理上传的文件并将其保存到服务器上。allowed_file() 函数检查文件扩展名是否允许上传。index() 函数返回上传页面,uploaded_file() 函数显示上传的图片。

为了使此程序工作,您需要创建两个 HTML 模板。这里是一个简单的 upload.html 模板:

<!doctype html>
<html>
    <head>
        <title>Upload</title>
    </head>
    <body>
        <h1>Upload a file</h1>
        <form method="POST" action="/upload" enctype="multipart/form-data">
            <input type="file" name="file">
            <br>
            <input type="submit" value="Upload">
        </form>
    </body>
</html>

这里是 uploaded.html 模板:

<!doctype html>
<html>
    <head>
        <title>Uploaded</title>
    </head>
    <body>
        <h1>Uploaded file:</h1>
        <img src="{{ url_for('static', filename='uploads/' + filename) }}" alt="Uploaded file">
    </body>
</html>

注意,uploaded.html 模板中的 src 属性使用 Flask 的 url_for() 函数来生成图片的 URL。

app.config['UPLOAD_FOLDER'] 中指定的文件夹应该是存在的,否则会抛出异常。可以在服务器上的根目录下创建一个名为 "uploads" 的文件夹并赋予其适当的权限。

python 制作一个能够上传图片的网页

原文地址: http://www.cveoy.top/t/topic/bD8y 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录