Node JS Express:上传文件

时间:2018-07-04 11:50:24

标签: node.js mongodb express mongoose gridfs

我要发送文件:

// Upload a file from loca file-system to MongoDB
app.post('/api/file/upload', (req, res) => {

    var filename = req.query.filename;
    //  here ..... request please 

    console.log(file + " and" + tempPath );

    var writestream = gfs.createWriteStream({ filename: filename });
    fs.createReadStream(__dirname + "/uploads/" + filename).pipe(writestream);
    writestream.on('close', (file) => {
        res.send('Stored File: ' + file.filename);
    });
});

在与Postman进行的API测试中,我想将文件发送到猫鼬(Gridfs)

1 个答案:

答案 0 :(得分:0)

如何使用https://www.npmjs.org/package/gridfs-stream

var fs = require('fs');
var mongoose = require("mongoose");
var Grid = require('gridfs-stream');
var GridFS = Grid(mongoose.connection.db, mongoose.mongo);


app.post('/api/file/upload', (req, res) => {

    var writestream = GridFS.createWriteStream({
        filename: req.query.filename
    });

    writestream.on('close', function (file) {
      callback(null, file);
    });

    fs.createReadStream(path).pipe(writestream);
});

请注意,路径是本地系统上文件的路径。