2023.11.17使用flask将多个图片文件上传至服务器

2023.11.17使用flask将多个图片文件上传至服务器

实现功能:

1、同时上传多个图片文件

2、验证文件扩展名

3、显示上传文件的文件名

4、显示文件上传结果

程序结构

main.py

复制代码
from flask import Flask, request, jsonify, render_template
import os

app = Flask(__name__)

# 设置上传文件存储目录
UPLOAD_FOLDER = 'uploads'
app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER

# 允许上传的文件类型
ALLOWED_EXTENSIONS = {'png', 'jpg', 'jpeg', 'gif'}

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

# 检查文件名是否合法
def allowed_file(filename):
    return '.' in filename and filename.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONS

# 处理文件上传
@app.route('/upload', methods=['POST'])
def upload_file():
    files = request.files.getlist("file")
    success_files = []
    failed_files = []

    for file in files:
        if file and allowed_file(file.filename):
            filename = file.filename
            file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename))
            success_files.append(filename)
        else:
            failed_files.append(file.filename)

    if failed_files:
        return jsonify({'message': '部分文件上传失败', 'failed_files': failed_files})
    else:
        return jsonify({'message': '所有文件上传成功', 'success_files': success_files})

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

index.html

复制代码
<!DOCTYPE html>
<html>
<head>
    <title>文件上传</title>
    <link href="https://cdn.staticfile.org/twitter-bootstrap/5.1.1/css/bootstrap.min.css" rel="stylesheet">
    <script src="https://cdn.staticfile.org/twitter-bootstrap/5.1.1/js/bootstrap.bundle.min.js"></script>
</head>
<body>
    <div class="container">
        <h1 class="mt-5 mb-4">文件上传</h1>
        <form id="upload-form" action="/upload" method="post" enctype="multipart/form-data">
            <div class="custom-file mb-3">
                <input type="file" class="custom-file-input" id="fileInput" name="file" multiple>
                <label class="custom-file-label" for="fileInput">选择文件</label>
            </div>
            <button type="submit" class="btn btn-primary">上传</button>
        </form>

        <div id="result" class="mt-3"></div>
    </div>

    <script>
        document.getElementById('upload-form').addEventListener('submit', function(e) {
            e.preventDefault();

            var formData = new FormData(this);

            fetch('/upload', {
                method: 'POST',
                body: formData
            })
            .then(response => response.json())
            .then(data => {
                if (data.failed_files) {
                    document.getElementById('result').innerHTML = '<div class="alert alert-danger" role="alert">部分文件上传失败: ' + data.failed_files.join(', ') + '</div>';
                } else {
                    document.getElementById('result').innerHTML = '<div class="alert alert-success" role="alert">' + data.message + '</div>';
                }
            })
            .catch(error => {
                console.error(error);
            });
        });

        // 更新文件选择框显示已选择的文件名
        document.getElementById('fileInput').addEventListener('change', function () {
            var files = this.files;
            var label = "";
            for (var i = 0; i < files.length; i++) {
                label += files[i].name + ', ';
            }
            // /,$/ 表示匹配以逗号结尾的部分。即将最后一个逗号清除
            label = label.replace(/, $/, "");
            this.nextElementSibling.innerText = label;
        });
    </script>
</body>
</html>
相关推荐
invicinble2 小时前
对linux形成认识
linux·运维·服务器
冷雨夜中漫步3 小时前
Python快速入门(6)——for/if/while语句
开发语言·经验分享·笔记·python
技术路上的探险家3 小时前
8 卡 V100 服务器:基于 vLLM 的 Qwen 大模型高效部署实战
运维·服务器·语言模型
郝学胜-神的一滴3 小时前
深入解析Python字典的继承关系:从abc模块看设计之美
网络·数据结构·python·程序人生
百锦再3 小时前
Reactive编程入门:Project Reactor 深度指南
前端·javascript·python·react.js·django·前端框架·reactjs
半桔3 小时前
【IO多路转接】高并发服务器实战:Reactor 框架与 Epoll 机制的封装与设计逻辑
linux·运维·服务器·c++·io
绵绵细雨中的乡音3 小时前
深入理解 ET 与 LT 模式及其在 Reactor 模型中的应用
服务器·网络·php
HABuo4 小时前
【linux文件系统】磁盘结构&文件系统详谈
linux·运维·服务器·c语言·c++·ubuntu·centos
Howrun7774 小时前
关于Linux服务器的协作问题
linux·运维·服务器
喵手5 小时前
Python爬虫实战:旅游数据采集实战 - 携程&去哪儿酒店机票价格监控完整方案(附CSV导出 + SQLite持久化存储)!
爬虫·python·爬虫实战·零基础python爬虫教学·采集结果csv导出·旅游数据采集·携程/去哪儿酒店机票价格监控