Python创建上传接口
时间: 2024-07-05 20:00:39 浏览: 72
Python接口测试文件上传实例解析
在Python中,创建一个文件上传接口通常涉及到Web开发和文件处理。这里我们可以使用Flask或Django等流行的Web框架,结合HTML表单来实现这个功能。以下是一个简单的示例,使用Flask:
```python
from flask import Flask, request, send_from_directory
app = Flask(__name__)
# 设置静态文件目录,上传文件将保存在这里
UPLOAD_FOLDER = 'uploads'
app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER
# 允许指定类型的文件上传
ALLOWED_EXTENSIONS = {'txt', 'pdf', 'png', 'jpg', 'jpeg'}
def allowed_file(filename):
return '.' in filename and filename.rsplit('.', 1).lower() in ALLOWED_EXTENSIONS
@app.route('/upload', methods=['POST'])
def upload_file():
if 'file' not in request.files:
return 'No file part'
file = request.files['file']
if file.filename == '':
return 'No selected file'
if file and allowed_file(file.filename):
filename = secure_filename(file.filename)
file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename))
return f"File {filename} uploaded successfully."
else:
return "Invalid file type."
if __name__ == '__main__':
app.run(debug=True)
阅读全文