Flask 之 文件上传并解压缩

# -*- coding: utf-8 -*-


from flask import Flask, request, render_template_string
import os
import zipfile
import tarfile

app = Flask(__name__)


@app.route('/')
def index():
    return render_template_string('''
   <form action="{{ url_for('upload_file') }}" method="post" enctype="multipart/form-data">
    <input type="file" name="file" required>
    <button type="submit">Upload</button>
</form>
    ''')


@app.route('/upload', methods=['POST'])
def upload_file():
    # 获取上传的文件
    file = request.files['file']

    # 检查文件扩展名
    if file.filename.endswith('.zip'):
        return parse_zip_file(file)
    elif file.filename.endswith('.tar.gz'):
        return parse_tar_gz_file(file)
    else:
        return 'Unsupported file type', 400


def parse_zip_file(file):
    # 保存文件到磁盘
    file_path = os.path.join('uploads', file.filename)
    file.save(file_path)

    # 解压 zip 文件
    with zipfile.ZipFile(file_path, 'r') as zip_ref:
        zip_ref.extractall('uploads')

    # 处理解压后的文件
    # ...

    return 'File uploaded and extracted successfully'


def parse_tar_gz_file(file):
    # 保存文件到磁盘
    file_path = os.path.join('uploads', file.filename)
    file.save(file_path)

    # 解压 tar.gz 文件
    with tarfile.open(file_path, 'r') as tar_ref: # mode 为 r 更通用
        tar_ref.extractall('uploads')

    # 处理解压后的文件
    # ...

    return 'File uploaded and extracted successfully'


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

posted @   染指未来  阅读(30)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· DeepSeek 开源周回顾「GitHub 热点速览」
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· AI与.NET技术实操系列(二):开始使用ML.NET
· 单线程的Redis速度为什么快?
历史上的今天:
2019-07-01 Python进阶(十一)----包,logging模块
点击右上角即可分享
微信分享提示