# -*- 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
python通过接口上传zip文件并解压文件到指定目录
最新推荐文章于 2024-11-24 16:00:00 发布
1330

被折叠的 条评论
为什么被折叠?



