flask 上传文件去重 前后端代码 mongodb数据库
时间: 2023-10-15 18:04:32 浏览: 74
前端代码:
```
<form action="/upload" method="POST" enctype="multipart/form-data">
<input type="file" name="file">
<button type="submit">Upload</button>
</form>
```
后端代码:
```
from flask import Flask, request, jsonify
from pymongo import MongoClient
import hashlib
app = Flask(__name__)
client = MongoClient('mongodb://localhost:27017/')
db = client['test']
collection = db['files']
@app.route('/upload', methods=['POST'])
def upload_file():
file = request.files['file']
file_hash = hashlib.md5(file.read()).hexdigest()
if collection.find_one({'hash': file_hash}):
return jsonify({'message': 'File already exists'})
else:
file.seek(0)
file.save('uploads/' + file.filename)
collection.insert_one({'filename': file.filename, 'hash': file_hash})
return jsonify({'message': 'File uploaded successfully'})
if __name__ == '__main__':
app.run(debug=True)
```
这里使用了 MongoDB 数据库来存储文件的哈希值,如果文件已经存在,则返回错误信息,否则将文件保存到本地并将文件名和哈希值存储到数据库中。
阅读全文