18

我试图弄清楚如何将图像直接发布到 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);

保存图片.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;

任何帮助将不胜感激!

4

5 回答 5

18

gridfs-stream让这很容易:

// `gfs` is a gridfs-stream instance
app.post('/picture', function(req, res) {
  req.pipe(gfs.createWriteStream({
    filename: 'test'
  }));
  res.send("Success!");
});
于 2013-12-31T17:41:08.937 回答
2

虽然@robertklep 的回答是正确的,但我想在他的回答中添加一些内容。此代码显示了如何发送回存储文件的元数据。

app.post('/picture', function(req, res) {
  req.pipe(gfs.createWriteStream({
    filename: 'test'
  }).on('close', function(savedFile){
    console.log('file saved', savedFile);
    return res.json({file: savedFile});
  }));
})  
于 2015-12-12T11:43:32.837 回答
1

这对我和猫鼬有用:

 var gfs = Grid(mongoose.connection.db, mongoose.mongo);
    var writeStream = gfs.createWriteStream({
        filename: name,
        mode: 'w',
        content_type: 'video/mp4'
    });
    writeStream.on('close', function() {
        console.log('close event');
    });

    fs.createReadStream('uploads/' + name + '/' + name + '.mp4').pipe(writeStream);
    console.log('stream.write: ' + name + '/' + name + '.mp4');

我正在为在客户端浏览器上获取视频而苦苦挣扎了几天。这就是我到目前为止所尝试的:

var readstream = gfs.createReadStream({
        filename: file.filename
    });

    readstream.on('data', function(data) {
        res.write(data);
        console.log(data);
    });

    readstream.on('end', function() {
        res.end();        
    });

    readstream.on('error', function (err) {
        console.log('An error occurred!', err);
        throw err;
    });

我在 MongoDB 方面的数据如下所示:

db.fs.chunks.find() {“_id”:ObjectId(“5757e76df14741bf0391aaca”),“files_id”:ObjectId(“5757e76df14741bf0391aac8”),“n”:0,“data”:BinData(0,“AAAAIGZ0eXBpc29.. ..

contentType 是“video/mp4”:

在浏览器端登录打印:

对象 { 0:“�”,1:“�”,2:“�”,3:“”,4:“f”,5:“t”,6:“y”,7:“p”,8 : "i", 9: "s", 85003 更多... }

有人可以救我的命吗?我希望你不要在这个地方看到我的帖子不方便。

于 2016-06-08T15:14:48.323 回答
0

使用nodejs中的gridfs在mongodb中插入txtfile的完整代码。这很好用`

var mongoose=require("mongoose");
var gridfsstream=require("gridfs-stream");
var fs=require("fs");
mongoose.connect("mongodb://localhost:27017/testimage");
var conn=mongoose.connection;
gridfsstream.mongo=mongoose.mongo;
conn.once("open",function()
{
    console.log("database connected successfully");
    var gfs=gridfsstream(conn.db);
    var writestream=gfs.createWriteStream({
        filename:"danger.txt"
    });
    fs.createReadStream("sivakasi.txt").pipe(writestream);
    writestream.on("close",function(file)
    {
        console.log(file.filename +"stored successfully into mongodb using gridfs");
    });
    writestream.on("error",function(file)
    {
        console.log(file.filename +"not stored into mongodb using gridfs");
    });
});
conn.on("error",function()
{
    console.log("database not connected try again!!!");
});

`

于 2017-01-07T15:57:58.023 回答
0

将图像从 html 发布到 nodejs 的完整代码使用 gridfs 系统将该图像存储在 mongodb 中并在服务器中显示该图像。此代码运行良好。

var express=require("express");
var bodyparser=require("body-parser");
var multer=require("multer");
var app=express();
var upload = multer({ dest: '/tmp/'});
app.use(bodyparser.urlencoded({extended:false}));
app.post("/uploadimage",upload.single("file"),function(request,response)
{
    var mongoose=require("mongoose");
    var gridfsstream=require("gridfs-stream");
    var fs=require("fs");
    mongoose.connect("mongodb://localhost:27017/testimage");
    var con=mongoose.connection;
    gridfsstream.mongo=mongoose.mongo;
    con.once("open",function()
    {
        console.log("test image database connected successfully");
        var gfs=gridfsstream(con.db);
        var readstream=fs.createReadStream(request.file.originalname);
        var writestream=gfs.createWriteStream({
            filename:"mentorpicthree.jpg"
        });
        readstream.pipe(writestream);
        writestream.on("close",function()
        {
            console.log("image stored in mongodb database successfully");
            fs.readFile(request.file.originalname,function(err,data)
            {
                if(err)
                {
                    response.writeHead(404,{"Content-Type":"text/plain"});
                    console.log("error");

                }
                else
                {
                        response.writeHead(200,{"Content-Type":"image/jpg"});
                        response.end(data);
                }
            });
        });
        writestream.on("error",function()
        {
            console.log("image not stored in mongodb database");
        });

    });
    con.on("error",function()
    {
        console.log("database not connected try again!!!");
    });

});
app.listen(8086,function()
{
    console.log("server running on port 8086");
});
<html>
<head>
    <title>FILE UPLOAD</title>
</head>
<body>
<p>Ryan Dhal</p>
<form action="http://127.0.0.1:8086/uploadimage" method="POST" enctype="multipart/form-data">
    <input type="file" name="file">
    <br>
    <input type="submit" value="UPLOAD">
</form>
</body>
</html>

于 2017-01-07T16:06:48.380 回答