# -*- 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()