Storing data stream from POST request in GridFS, express, mongoDB, node.js

后端 未结 5 1731
予麋鹿
予麋鹿 2020-12-01 05:53

I am trying to figure out how I can post an image directly to GridFS without storing it anywhere on the server as a temporary file first.

I am using Postman (chrome

5条回答
  •  难免孤独
    2020-12-01 06:32

    This worked for me with mongoose:

     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');
    

    I am struggling a couple of days with getting the video on client side browser. That is what I tried so far:

    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;
        });
    

    My Data on MongoDB side looks like:

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

    And the contentType is 'video/mp4':

    logging on browser side prints this:

    Object { 0: "�", 1: "�", 2: "�", 3: " ", 4: "f", 5: "t", 6: "y", 7: "p", 8: "i", 9: "s", 85003 more… }

    Could someone please save my live? I hope you do not see my post as not convenient in this place.

提交回复
热议问题