python3部署文件服务器,支持curl命令上传文件
-
上传命令
curl -F "file=@file.txt" http://x.x.x.x:5000/upload -
file-server.py
from flask import Flask, request, redirect, url_for, send_from_directory, flash, jsonify
import os
app = Flask(__name__)
# 设置上传文件的保存目录
UPLOAD_FOLDER = '/upload'
app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER
# 确保上传目录存在
if not os.path.exists(UPLOAD_FOLDER):
os.makedirs(UPLOAD_FOLDER)
# 允许上传的文件扩展名
ALLOWED_EXTENSIONS = {'gz', 'txt', 'pdf', 'png', 'jpg', 'jpeg', 'gif'}
def allowed_file(filename):
return True
#return '.' in filename and \
# filename.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONS
@app.route('/upload', methods=['POST'])
def upload_file():
# 检查请求中是否包含文件部分
if 'file' not in request.files:
return jsonify({'error': 'No file part'}), 400
file = request.files['file']
# 如果用户没有选择文件
if file.filename == '':
return jsonify({'error': 'No selected file'}), 400
if file and allowed_file(file.filename):
filename = file.filename
file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename))
return jsonify({'message': 'File successfully uploaded', 'filename': filename}), 200
return jsonify({'error': 'File type not allowed'}), 400
# 路由以提供上传的文件(可选)
@app.route('/uploads/<filename>')
def uploaded_file(filename):
return send_from_directory(app.config['UPLOAD_FOLDER'], filename)
if __name__ == '__main__':
app.run(host='0.0.0.0', port=5000, debug=True)

浙公网安备 33010602011771号