gpt4 book ai didi

javascript - 在 GridFS、express、mongoDB、node.js 中存储来自 POST 请求的数据流

转载 作者:太空宇宙 更新时间:2023-11-04 02:36:14 24 4
gpt4 key购买 nike

我试图弄清楚如何将图像直接发布到 GridFS,而不首先将其作为临时文件存储在服务器上的任何位置。

我正在使用 Postman(chrome ext.)来发布文件,并且我设法使用以下方法将这篇文章存储为文件:

req.pipe(fs.createWriteStream('./test.png'));

当从服务器上的文件创建 readStream 时,我还可以将 readStream 直接存储到 GridFS。 (见代码)

我有以下文件,saveFromReq.js,它监听 POST 并基本上将其传递给 savePic.js

saveFromReq.js:

var express = require('express');
var app = express();
var savePic = require('./savePic');
var fs = require('fs');
var GridStore = require('mongodb').GridStore;
var pic = './square.png';
var picID;



//When the following

//var pic = fs.createReadStream('./square.png', {autoClose: true});

//is not commented out, and 'req' is replaced with 'pic' in the savePic function,
//the file square.png is stored correctly to GridFS

app.post('/picture', function(req, res){

savePic(req, function(id){});
res.writeHead(200, {'Content-Type': 'text' });
res.end("Sucsess!\n");

});

app.listen(process.env.PORT || 3413);

savePic.js:

var savePic = function(req, callback){


var Db = require('mongodb').Db,
MongoClient = require('mongodb').MongoClient,
Server = require('mongodb').Server,
ReplSetServers = require('mongodb').ReplSetServers,
ObjectID = require('mongodb').ObjectID,
Binary = require('mongodb').Binary,
GridStore = require('mongodb').GridStore,
Grid = require('mongodb').Grid,
Code = require('mongodb').Code,
BSON = require('mongodb').pure().BSON,
assert = require('assert');
fs = require('fs');

//When the following

//req.pipe(fs.createWriteStream('./test.png'));

//is not commented out, the correct image is stored to test.png, and
//the sequence after req.on("data"... starts
//(That sequence does not start at all when this is commented out..)

var fileId = new ObjectID();
var db = new Db('testDB', new Server('localhost', 27017));
// Establish connection to db
db.open(function(err, db) {


var gridStore = new GridStore(db, 'test', 'w');

//open
gridStore.open(function(err, gridStore) {
console.log("opened");


req.on("data", function (data) {
console.log("data recieved");
gridStore.write(data, function (err, gridStore) {
if (err) {
console.log("error writing file");
}
});
});
req.on("end", function () {
gridStore.close(function (err, gridStore) {
if (!err) {
console.log("The file has been stored to database.");
db.close();
}
});
});
req.pipe(gridStore);


});




});
callback(fileId);
};
module.exports = savePic;

任何帮助将不胜感激!

最佳答案

gridfs-stream让这变得很容易:

// `gfs` is a gridfs-stream instance
app.post('/picture', function(req, res) {
req.pipe(gfs.createWriteStream({
filename: 'test'
}));
res.send("Success!");
});

关于javascript - 在 GridFS、express、mongoDB、node.js 中存储来自 POST 请求的数据流,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22140001/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com