flask mongodb文件的上传和下载 前后端代码
时间: 2023-06-02 16:03:09 浏览: 110
后端代码:
1. 安装flask和pymongo库
```
pip install flask pymongo
```
2. 创建Flask应用程序,配置数据库连接
```
from flask import Flask, request, send_file
from pymongo import MongoClient
app = Flask(__name__)
# 配置数据库连接
client = MongoClient('mongodb://localhost:27017/')
db = client['test']
collection = db['files']
```
3. 编写文件上传接口
```
@app.route('/upload', methods=['POST'])
def upload_file():
file = request.files['file']
filename = file.filename
# 将文件保存到MongoDB数据库中
collection.insert_one({'filename': filename, 'file': file.read()})
return '文件上传成功'
```
4. 编写文件下载接口
```
@app.route('/download/<filename>', methods=['GET'])
def download_file(filename):
# 从数据库中查询文件
file = collection.find_one({'filename': filename})
# 将文件下载到本地
return send_file(file['file'], attachment_filename=file['filename'], as_attachment=True)
```
前端代码:
1. HTML页面中添加上传和下载按钮
```
<form action="/upload" method="post" enctype="multipart/form-data">
<input type="file" name="file">
<button type="submit">上传文件</button>
</form>
<a href="/download/test.txt">下载文件</a>
```
2. 使用JavaScript实现文件上传和下载
```
// 文件上传
let fileInput = document.querySelector('input[type="file"]');
let uploadButton = document.querySelector('button[type="submit"]');
uploadButton.addEventListener('click', () => {
let formData = new FormData();
formData.append('file', fileInput.files[0]);
fetch('/upload', {
method: 'POST',
body: formData
}).then(response => {
console.log(response.text());
});
});
// 文件下载
let downloadLink = document.querySelector('a[href^="/download/"]');
downloadLink.addEventListener('click', event => {
event.preventDefault();
let filename = downloadLink.getAttribute('href').split('/').pop();
fetch(`/download/${filename}`).then(response => {
response.blob().then(blob => {
let url = URL.createObjectURL(blob);
let a = document.createElement('a');
a.href = url;
a.download = filename;
a.click();
});
});
});
```
阅读全文