使用Python编写APIWebAPI()实现文件的上传和下载功能
发布时间:2024-01-17 05:20:29
使用Python编写API实现文件的上传和下载功能可以使用Flask框架来实现。下面是一个简单的示例代码:
from flask import Flask, request, send_file
import os
app = Flask(__name__)
# 文件上传接口
@app.route('/upload', methods=['POST'])
def upload_file():
if 'file' not in request.files:
return 'No file uploaded', 400
file = request.files['file']
if file.filename == '':
return 'No file selected', 400
filename = file.filename
file.save(filename)
return 'File uploaded successfully!'
# 文件下载接口
@app.route('/download/<path:filename>', methods=['GET'])
def download_file(filename):
if not os.path.isfile(filename):
return 'File not found', 404
return send_file(filename, as_attachment=True)
if __name__ == '__main__':
app.run(debug=True)
上面的代码使用了Flask框架来创建一个API服务。其中,/upload接口可以用来上传文件,/download/<filename>接口可以用来下载文件。通过不同的HTTP方法和URL路径来区分不同的功能。
可以使用curl命令或者Postman来测试API。
上传文件的示例命令:
curl -X POST -F 'file=@/path/to/file' http://localhost:5000/upload
下载文件的示例命令:
curl -OJ http://localhost:5000/download/filename
以上是一个简单的文件上传和下载的API实现,可以根据实际需求进行扩展和修改。
