以下是使用 GridFS 的基本概念和操作:
存储文件到 GridFS:
1. 连接到数据库:
const { MongoClient } = require('mongodb');
const client = new MongoClient('mongodb://localhost:27017', { useNewUrlParser: true, useUnifiedTopology: true });
client.connect(async err => {
if (err) throw err;
const database = client.db('mydatabase');
const bucket = new database.GridFSBucket();
});
2. 打开文件并写入 GridFS:
const fs = require('fs');
const input = fs.createReadStream('path/to/your/file');
const uploadStream = bucket.openUploadStream('filename.txt');
input.pipe(uploadStream);
input.on('end', () => {
console.log('File uploaded successfully');
client.close();
});
从 GridFS 中检索文件:
1. 连接到数据库:
const { MongoClient } = require('mongodb');
const client = new MongoClient('mongodb://localhost:27017', { useNewUrlParser: true, useUnifiedTopology: true });
client.connect(async err => {
if (err) throw err;
const database = client.db('mydatabase');
const bucket = new database.GridFSBucket();
});
2. 从 GridFS 中检索文件:
const fs = require('fs');
const downloadStream = bucket.openDownloadStreamByName('filename.txt');
const output = fs.createWriteStream('path/to/save/file');
downloadStream.pipe(output);
output.on('finish', () => {
console.log('File downloaded successfully');
client.close();
});
删除 GridFS 中的文件:
bucket.delete('filename.txt', err => {
if (err) throw err;
console.log('File deleted successfully');
client.close();
});
上述代码中的 'filename.txt' 是文件在 GridFS 中的标识符。
注意:上述代码只是一个简单的演示,实际使用时可能需要更多的错误处理和逻辑。确保在生产环境中考虑到文件上传和下载的安全性和性能。
转载请注明出处:http://www.zyzy.cn/article/detail/14250/MongoDB