2023.11.19使用flask制作一个文件夹生成器

2023.11.19使用flask制作一个文件夹生成器

实现功能:

(1)在指定路径上建立文件夹

(2)返回文件夹的路径和建立成功与否的提示

main.py

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

app = Flask(__name__)

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


@app.route('/create_folder', methods=['POST'])
def create_folder():
    folder_name = request.json['folder_name'] # 获取前端传递的文件夹名称

    # 指定路径和文件夹名称
    base_path = 'static'  # 替换为实际的路径
    folder_path = os.path.join(base_path, folder_name)

    try:
        os.makedirs(folder_path)  # 在指定路径创建文件夹
        response = {
            'message': '文件夹创建成功',
            'folder_path': folder_path
        }
        return jsonify(response)
    except Exception as e:
        response = {
            'message': '文件夹创建失败',
            'error': str(e)
        }
        return jsonify(response), 500

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

index.html

复制代码
<!DOCTYPE html>
<html>
<head>
    <title>创建文件夹</title>
</head>
<body>
    <h2>创建文件夹</h2>
    <input type="text" id="folderName" placeholder="请输入文件夹名称">
    <button onclick="createFolder()">创建</button>
    <p id="response"></p>

    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    <script>
        function createFolder() {
            var folderName = $('#folderName').val();

            $.ajax({
                url: '/create_folder',
                type: 'POST',
                contentType: 'application/json',
                data: JSON.stringify({ 'folder_name': folderName }),
                success: function(response) {
                    $('#response').text(response.message + ',路径为:' + response.folder_path);
                },
                error: function(xhr, status, error) {
                    var errorMessage = xhr.responseText ? JSON.parse(xhr.responseText).message : '请求失败';
                    $('#response').text('错误:' + errorMessage);
                }
            });
        }
    </script>
</body>
</html>
相关推荐
JinSo35 分钟前
我的2025年度总结:EasyEditor
前端·程序员
cnxy1885 小时前
围棋对弈Python程序开发完整指南:步骤1 - 棋盘基础框架搭建
开发语言·python
喝拿铁写前端5 小时前
前端开发者使用 AI 的能力层级——从表面使用到工程化能力的真正分水岭
前端·人工智能·程序员
落叶,听雪5 小时前
河南建站系统哪个好
大数据·人工智能·python
上进小菜猪5 小时前
基于 YOLOv8 的驾驶员疲劳状态识别系统实战(含完整源码与可视化界面)
后端
wuhen_n5 小时前
LeetCode -- 15. 三数之和(中等)
前端·javascript·算法·leetcode
上进小菜猪5 小时前
基于 YOLOv8 的交通标识与设施识别系统(含完整源码)
后端
七月shi人6 小时前
AI浪潮下,前端路在何方
前端·人工智能·ai编程
非凡ghost6 小时前
MusicPlayer2(本地音乐播放器)
前端·windows·学习·软件需求