0

我已经使用“Multer”和“multer-gridfs-storage”将多个图像文件上传到 MongoDB。我想提取这些文件并将它们显示为网页上的缩略图。我试图将这些文件提取到 ReadStream 并将它们存储到我可以循环的数组中。

var streams = [];
    console.log(result)
    for (var i = 0; i < result.length; i++) {

        var gfs = Grid(conn.db);
        var campground = gfs.createReadStream({
            _id: result[i]._id
        });
        streams[i] = campground;
        console.log("   " + i);
    }

我想将这些传递到可以显示它们的前端,但它们没有显示。我尝试循环运行以下代码。

    var rest
    streams[0].pipe(rest)
    res.writeHead(200, { 'Content-Type': 'image/jpeg' });
    res.write(rest);
    //      res.addTrailers({ 'image/jpeg': rest });
    res.end();

不管用。以下工作但只显示一个文件

 streams[i].pipe(res)

我想将图像数组传递给我的 ejs 文件。stream[i] 数组是网格对象,而不是最终图像。我如何做到这一点?

问候, 高拉夫

4

2 回答 2

2

经过一番搜索得到了答案

    const bufs = [];
    readstream.on('data', function(chunk) {
        bufs.push(chunk);
    });
    readstream.on('end', function() {
        const fbuf = Buffer.concat(bufs);
        res.setHeader('Content-Type', 'image/jpeg');
        res.writeHead(res.statusCode);
        res.write(fbuf);
        /res.end();

    });
于 2017-12-07T09:51:47.660 回答
0

不知道你是否还在寻找,但这里我正在使用:

var gfs = Grid(req.conn.db, mongoose.mongo);
var fileId = new mongoose.Types.ObjectId();
var fileName = file.filename;

//Create a gridfs-stream into which we pipe multer's temporary file saved in uploads
var writestream = gfs.createWriteStream({
    _id: fileId,
    filename: file.originalname,
    aliases: fileName
});

//Pipe multer's temp file /uploads/filename into the stream we created above.
fs.createReadStream(imgDir + fileName)
    .on("end", function () {
        // something
    })
    .on("err", function () {
        var msg = 'Erro enviando imagem para o  banco de dados';
        req.flash('error_msg', msg);
    })
    .pipe(writestream);
于 2018-06-18T13:31:29.120 回答