flask实现从七牛云上下载文件,前后端代码
时间: 2023-10-29 10:08:44 浏览: 42
前端代码:
```html
<!DOCTYPE html>
<html>
<head>
<title>Download file from QiNiu Cloud</title>
</head>
<body>
<form method="post" action="{{ url_for('download') }}">
<label for="file-key">File Key:</label>
<input type="text" id="file-key" name="file_key">
<input type="submit" value="Download">
</form>
</body>
</html>
```
后端代码:
```python
from flask import Flask, render_template, request, send_from_directory
import qiniu
import os
app = Flask(__name__)
@app.route('/')
def index():
return render_template('index.html')
@app.route('/download', methods=['POST'])
def download():
# 获取表单数据
file_key = request.form['file_key']
# 获取七牛云的access_key和secret_key
access_key = os.environ.get('QINIU_ACCESS_KEY')
secret_key = os.environ.get('QINIU_SECRET_KEY')
# 构建鉴权对象
auth = qiniu.Auth(access_key, secret_key)
# 获取文件的下载链接
bucket = 'your-bucket-name'
domain = 'your-bucket-domain'
private_url = qiniu.private_download_url(domain + '/' + file_key, expires=3600, auth=auth)
# 下载文件
return send_from_directory(directory='.', filename=file_key, as_attachment=True, attachment_filename=file_key)
```
注意:在使用这个代码之前,你需要先安装 `qiniu` 包并且了解如何获取七牛云的 `access_key` 和 `secret_key`。