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):
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)