MongoDB学习笔记之GridFS使用介绍
什么是GridFS
GridFS 是 MongoDB 提供的一种协议,用于存储可扩展的大型二进制数据文件,例如图像、音频和视频文件。MongoDB 的文件系统使用两个集合来存储二进制文件,使之可以分批读取或者分片存储。
如何使用GridFS
- 创建GridFS对象
创建GridFSBucket
对象时,必须指定数据库名称和集合名称,例如:
const { MongoClient } = require('mongodb');
const { GridFSBucket } = require('mongodb');
const uri = "mongodb+srv://<username>:<password>@cluster0.mongodb.net/test?retryWrites=true&w=majority";
const client = new MongoClient(uri);
async function run() {
try {
await client.connect();
console.log("Connected correctly to server");
const database = client.db('<database name>');
const bucket = new GridFSBucket(database, { bucketName: '<bucket name>' });
} catch (err) {
console.log(err.stack);
}
// Close the connection to the MongoDB server
await client.close();
}
run().catch(console.dir);
在该示例中,<username>
、<password>
、<database name>
和 <bucket name>
需要替换为实际值。
- 存储文件
使用openUploadStream
方法上传文件,例如:
const { ObjectId } = require('mongodb');
const fs = require('fs');
// An error will be thrown if the file does not exist
const readableStream = fs.createReadStream('<path to file>');
const uploadStream = bucket.openUploadStream('<filename>');
// Store custom metadata with the file
const metadata = { owner: "username", readPrivilege: true };
uploadStream.on('finish', function() {
console.log('File uploaded!')
console.log(`File ID: ${uploadStream.id}`);
});
// Pipe the file data to the GridFS file object
readableStream.pipe(uploadStream);
在该示例中,<path to file>
和 <filename>
需要替换为实际值。上传文件时可以选择存储自定义的文件元数据(例如上传者信息等)。
- 下载文件
使用openDownloadStream
方法下载文件,例如:
const downloadStream = bucket.openDownloadStream(ObjectId('<file ID>'));
// Pipe the file data to the response object
downloadStream.pipe(response);
在该示例中,<file ID>
需要替换为实际值。下载文件时可以将文件数据直接发送到响应对象,以便实现断点续传等功能。
示例说明
- 上传文件
const { MongoClient } = require('mongodb');
const { GridFSBucket } = require('mongodb');
const fs = require('fs');
const uri = "mongodb+srv://<username>:<password>@cluster0.mongodb.net/test?retryWrites=true&w=majority";
const client = new MongoClient(uri);
async function run() {
try {
await client.connect();
console.log("Connected correctly to server");
const database = client.db('<database name>');
const bucket = new GridFSBucket(database, { bucketName: '<bucket name>' });
const readableStream = fs.createReadStream('<path to file>');
const uploadStream = bucket.openUploadStream('<filename>');
const metadata = { owner: "username", readPrivilege: true };
uploadStream.on('finish', function() {
console.log('File uploaded!')
console.log(`File ID: ${uploadStream.id}`);
});
readableStream.pipe(uploadStream);
} catch (err) {
console.log(err.stack);
}
await client.close();
}
run().catch(console.dir);
在该示例中,替换 <username>
、<password>
、<database name>
、<bucket name>
、<path to file>
和 <filename>
为实际值。运行该脚本后,将会上传指定路径下的文件到 GridFS,并打印出文件 ID。
- 下载文件
const { MongoClient } = require('mongodb');
const { GridFSBucket } = require('mongodb');
const fs = require('fs');
const uri = "mongodb+srv://<username>:<password>@cluster0.mongodb.net/test?retryWrites=true&w=majority";
const client = new MongoClient(uri);
async function run() {
try {
await client.connect();
console.log("Connected correctly to server");
const database = client.db('<database name>');
const bucket = new GridFSBucket(database, { bucketName: '<bucket name>' });
const downloadStream = bucket.openDownloadStream(ObjectId('<file ID>'));
downloadStream.pipe(fs.createWriteStream('<path to output>'));
} catch (err) {
console.log(err.stack);
}
await client.close();
}
run().catch(console.dir);
在该示例中,替换 <username>
、<password>
、<database name>
、<bucket name>
、<file ID>
和 <path to output>
为实际值。运行该脚本后,将会下载指定 ID 的文件,并保存到指定路径下。
本站文章如无特殊说明,均为本站原创,如若转载,请注明出处:MongoDB学习笔记之GridFS使用介绍 - Python技术站