python通过接口上传zip文件并解压文件到指定目录

# -*- coding: utf-8 -*-
# @Time    : 2024/4/16 15:43
# @Author  : Cocktail_py
import os
import zipfile
from flask import Flask, request
from werkzeug.utils import secure_filename

app = Flask(__name__)

basefilepath = os.path.dirname(os.path.abspath('__file__')) + "/file"
folder_path = basefilepath + "/w1"


def unzip_file(zip_path, extract_to, overwrite=True):
    """解压zip文件"""
    if not os.path.exists(extract_to):
        os.makedirs(extract_to)

    with zipfile.ZipFile(zip_path, 'r') as zip_ref:
        for file in zip_ref.infolist():
            if file.filename.endswith('/'):  # 处理文件夹
                continue
            file_path = os.path.join(extract_to, file.filename)
            if os.path.exists(file_path) and overwrite:
                os.remove(file_path)  # 如果文件存在,则删除
            zip_ref.extract(file, extract_to)  # 提取文件


@app.route('/upload', methods=['POST'])
def upload_file():
    if 'file' not in request.files:
        return 'No file part', 400

    file = request.files['file']
    if file.filename == '':
        return 'No selected file', 400

    if file:
        filename = secure_filename(file.filename)
        file.save(os.path.join(basefilepath, filename))
        print("上传的文件名", filename)
        if os.path.exists(basefilepath + '/' + filename):
            # 解压文件
            # 使用例子
            # zip_file_path = 'example.zip'
            # extract_destination = 'extracted_files'
            # 解压并覆盖旧文件
            inventory_file = folder_path + ".zip"
            unzip_file(inventory_file, basefilepath, overwrite=True)
            pass
        else:
            return '上传文件不存在', 404
        # 判断文件是否存在
        return 'File uploaded successfully', 200


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

# curl -X POST -F "file=@/path/to/your/file" http://localhost:5000/upload

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Cocktail_py

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值