3

使用 FeathersJS 构建 REST API 我需要能够上传图片(POST),如果感谢 GridFS 进行记录,并且以后能够获取它。

我开始使用 Mongoose 设置 GridFS:

const mongoose = require('mongoose');
const Grid = require('gridfs-stream');
Grid.mongo = mongoose.mongo;

module.exports = function () {
  const app = this;

  mongoose.connect(app.get('mongodb'));
  const cnx = mongoose.connection;
  mongoose.Promise = global.Promise;

  cnx.once('open', () => {
    const gfs = Grid(cnx.db);
    app.set('gfs', gfs);
  })

  app.set('mongooseClient', mongoose);
};

然后添加我的/pub服务:

pub.service.js

const multipartMiddleware = require('multer')();
[...]
app.use('/pub', 
      multipartMiddleware.single('uri'),
      function(req, res, next){
        req.feathers.file = req.file;
        next();
      },
      createService(options)
    );

pub.hook.js

create: [
      hook => {
        const gfs = hook.app.get('gfs');
        const file = hook.params.file;

        console.log(hook)

        const writestream = gfs.createReadStream({
          filename: file.originalname,
          content_type: file.mimetype, // image/jpeg or image/png
        })
        const dir = __dirname;
        fs.createReadStream(`${__dirname}/img`).pipe(writestream);
      }
    ],

然后我收到一条错误消息:

MongoError:ID为###的文件未打开以进行写入

其中### 是文件名而不是_id

4

0 回答 0