flask mongodb文件的上传 上传文件 文件名重复的删掉 前后端代码
时间: 2024-05-09 08:20:22 浏览: 53
前端代码:
```
<form method="POST" enctype="multipart/form-data">
<input type="file" name="file">
<input type="submit" value="Upload">
</form>
```
后端代码:
```
from flask import Flask, request
from pymongo import MongoClient
import os
app = Flask(__name__)
# 连接MongoDB
client = MongoClient('localhost', 27017)
db = client['test']
collection = db['files']
# 上传文件
@app.route('/upload', methods=['POST'])
def upload_file():
file = request.files['file']
# 判断文件名是否重复
if collection.find_one({'name': file.filename}):
return 'File already exists!'
else:
# 保存文件
file.save(os.path.join(app.config['UPLOAD_FOLDER'], file.filename))
# 将文件信息存入MongoDB
collection.insert_one({'name': file.filename,
'path': os.path.join(app.config['UPLOAD_FOLDER'], file.filename)})
return 'File uploaded successfully!'
if __name__ == '__main__':
app.config['UPLOAD_FOLDER'] = '/path/to/upload/folder'
app.run()
```
注意:需要安装pymongo模块。
阅读全文