use*_*465 5 mongodb node.js gridfs
以下代码按预期工作:它读取已使用 multer [https://github.com/expressjs/multer] 上传的文件并将其流式传输到 gridfs。我也能够从 gridfs 中蒸出它。
var target = gfs.createWriteStream({
filename: fileItem.originalname,
mode: 'w',
metadata: metaData
});
fs.createReadStream(tempFile)
.on('end', function () {
console.log('File read and stored');
})
.on('error', function (err) {
console.log('Error handling file ' + err);
})
.pipe(target);
// Attach new file to document list
target.on('close', function (file) {
filesUploadedList.push(file._id);
Run Code Online (Sandbox Code Playgroud)
fileItem是通过迭代req.files.file上传的文件获得的。
但是,我正在尝试找出 multer 的 inMemory 选项。如果我将此设置为 true,fileItem则将填充缓冲区。请注意,如果没有此选项, 的缓冲区/内容fileItem是空的,这就是为什么在上面的代码中从fileItem.location.
用内容填充目标的最佳方法是什么?该fs.createReadStream做的那一刻管道。
谢谢。
J
您可以通过使用streamifier来完成此操作。代码看起来应该是这样的:
streamifier.createReadStream(fileItem.buffer).pipe(target);
Run Code Online (Sandbox Code Playgroud)
Multer 不会向磁盘写入任何内容,目标现在填充了正在上传的文件的缓冲区/内容。
你可以这样使用它:
(最初的想法是:使用 gridfs-stream 将文件直接存储在 mongodb 中)
app.post('/upload',multer({
dest:"./tmp/",
upload:null,// take uploading process
inMemory:true, //or false, not needed here
onFileUploadStart:function(file){
//set upload with WritableStream
this.upload = gfs.createWriteStream({
filename:file.originalname,
mode:"w",
chunkSize:1024*4,
content_type:file.mimetype,
root:"fs",
metadata: {} // put some crazy meta data in here
});
},
onFileUploadData:function(file,data) {
//put the chunks into db
this.upload.write(data);
},
onFileUploadComplete:function(file) {
//end process
this.upload.end();
console.log('successfully written File to MongoDB Gridfs');
}
}),
function(req,res) {
res.sendStatus(200);
});
Run Code Online (Sandbox Code Playgroud)
由于您使用的是 onFileUploadData() 函数,Gridsfs 将在数据到达时填充。无论 inMemory 设置为 true 或 false,这都有效。您应该注意,如果您正在处理大文件,则 file.buffer[] 可能会变得非常大。它只是所有传入数据片段的副本。
理论上,最好在Busboy之上使用自己定义的中间件,而不执行文件操作(如 Multer 中使用的)。
| 归档时间: |
|
| 查看次数: |
14249 次 |
| 最近记录: |