在NestJS中使用multer-gridfs流

时间:2019-03-20 10:20:42

标签: mongoose nestjs multer-gridfs-storage

我试图在nestjs中明确使用multer-gridfs-storage中间件。我想存储一个文件并使用gridfs-stream包检索它。但是对我来说没有任何用。我无法使用文件本身填充请求。每当我尝试打印请求对象时,它都没有与req.file或buffer元素相关的任何内容。而且我不确定一旦使用multer获取文件后如何处理该文件。

这是样本控制器方法

@Post('/uploadFiles')
    public async postFileToMongo(@Req() req, @Res() res) {

        //logger.info('this is the mutler upload details',req.body);
        //logger.info('coming inside upload files', req);
        logger.info('this is the sample value set');
        logger.info('this is the request body', req);
        logger.info('this is the request files', req.file);
        await this.fileStorageService.createFilesIntoGridFsUsingGridFSStream();
        res.send('Done');
    }

这是FileStorageService。我还没有实现multerStorage,因为我没有从控制器得到任何东西(req.file为空)

 @Injectable()
    export class FileStorageService {
      mongooseConnection: mongoose.Connection;
      gridfsConnection: GridFsStream.Grid;
      gridfsStorage: GridFSStorage;
      uploadStorage;
      constructor(
        @Inject(MONGO_DB_PROVIDER_TOKEN_TEST) private readonly mongoCon: Connection,
        private readonly configService : ConfigProviderService,
      ) {
        this.mongooseConnection = this.mongoCon as mongoose.Connection;

     this.gridfsConnection = GridFsStream(
            this.mongooseConnection.db,
            mongoose.mongo,
          );
        this.gridfsConnection.collection('default_collection');
          // now intialize the storage engine

        this.gridfsStorage = new GridFSStorage({
          db: this.mongooseConnection,
          cache: true,
          file: (req, file) => {

            // instead of just returning fileName or bucket Name as below
            // we could return an object 
            // let bucket;
            // if (file.mimetype === 'multipart/*' || file.mimetype === 'img/jpeg') {
            //   bucket = 'first_collection';
            // } else {
            //   bucket = 'second_collection';
            // }
            return {
              filename: file.originalname + Date.now(),
              bucketName: 'default_collection',
            }
          },
        });
        this.uploadStorage = multer({ storage: this.gridfsStorage });


        logger.info('gridfsConnection obj', isNullOrUndefined(this.gridfsConnection));
        //logger.info('upload storage vale', this.uploadStorage);
      }

    async createFilesIntoGridFsUsingGridFSStream() {
        //console.log(this.uploadStorage);
       const writeStream  =  this.gridfsConnection.createWriteStream({
            filename: 'doodle_test.png',
            mode: 'w',
            root: 'first_collect',
            chunkSize: 1024,
            metadata: {
              file_desc: 'This is a sample metadata added',
            },
        });
       const filestring = path.resolve('./doodle.png');
       await fs.createReadStream(filestring).pipe(writeStream).on('error', err => {
          logger.info('err ob', err);
        });
       writeStream.on('close', (file) => {
          logger.info('file name is', file.filename);
        });
      }

      async createFilesUsingMulter(req, ){

      }


    }

我什至尝试创建一个单独的中间件,但是它也不起作用

@Injectable()
export class FileStorageMiddlewareMiddleware implements NestMiddleware {
  mongooseConnection: Connection;
  constructor(@Inject(MONGO_DB_PROVIDER_TOKEN_TEST) private readonly mongoConnection: Connection,
              private readonly configService: ConfigProviderService){
    this.mongooseConnection = this.mongoConnection as mongoose.Connection;
  }
  resolve(...args: any[]): MiddlewareFunction {
    return (req, res, next) => {
      logger.info('inside file storage middleware');
      // const fileStorage = new multerGridfsStorage({
      //   // url: this.configService.getDBCred().$urlString,
      //   db: this.mongoConnection as Connection,
      //   cache: true,
      //   file :(req, file) => {
      //     //determine the default filename
      //     const filename = file.filename+'feedback_file_'+Date.now();
      //     let bucketname = 'default_file_collection';
      //     if(file.mimetype === 'plain/text') {
      //       bucketname = 'files.text';
      //     } else if(file.mimetype === 'plain/html'){
      //       bucketname = 'files.html'; 
      //     } else if(file.mimetype === 'img/png' || file.mimetype === 'img/jpeg' ||
      //       file.mimetype === 'img.jpg'){
      //       bucketname = 'files.image';
      //     }

      //     return {fileName: filename, bucketName: bucketname};
      //     // determing the bucketname
      //   },
      // });
      // const upload = multer({storage: fileStorage});

      // //upload.single('./../../../src/fileUpload');
      // //busboyBodyParser({ limit: '1kb' }, { multi: true });
      // // req.busboyBodyParser([{limit: '20mb'}, {multi: true}]);
      // upload.single('file');
      next();
    };
  }
}

注意:我包括中间件并将其使用在模块中。我可以在中间件中看到日志,但是看不到多形式零件数据

以下是“邮递员”工具的详细信息(使用3002作为端口,使用“开发” 作为上下文路径

enter image description here

这是我使用gridfs-stream模块遵循的过程,从本地文件夹中获取了一个样本文件,并将其存储在gridfs中,并且可以正常工作。

   async createFilesIntoGridFsUsingGridFSStream() {
this.gridfsConnection = GridFsStream(
            this.mongooseConnection.db,
            mongoose.mongo,
          );
        //console.log(this.uploadStorage);
       const writeStream  =  this.gridfsConnection.createWriteStream({
            filename: 'doodle_test.png',
            mode: 'w',
            root: 'first_collect',
            chunkSize: 1024,
            metadata: {
              file_desc: 'This is a sample metadata added',
            },
        });
       const filestring = path.resolve('./doodle.png');
       await fs.createReadStream(filestring).pipe(writeStream).on('error', err => {
          logger.info('err ob', err);
        });
       writeStream.on('close', (file) => {
          logger.info('file name is', file.filename);
        });
      }

但是有警告 我认为默认情况下,Gridfs使用GridStore并尝试将其存储在集合中

  

DeprecationWarning:GridStore已过时,将在   未来版本。请改用GridFSBucket(node:29332)   DeprecationWarning:不建议使用collection.ensureIndex。采用   改为使用createIndexes。 (节点:29332)弃用警告:   不推荐使用collection.save。使用insertOne,insertMany,updateOne,   或使用updateMany。

因此,我想利用默认情况下使用GridFSStorage的multer-gridfs-storage

以防万一,这里是版本详细信息

"@types/mongoose": "^5.3.20",
    "@types/multer": "^1.3.7",
    "@types/multer-gridfs-storage": "^3.1.1", "gridfs": "^1.0.0",
    "gridfs-stream": "^1.1.1",  "mongoose": "^5.4.11",
    "multer": "^1.4.1",
    "multer-gridfs-storage": "^3.2.3",

编辑:这是出于学习目的,希望深入了解如何在nestjs中处理快速中间件。我了解到nestjs具有类似于FileInterceptor的功能来处理文件,但希望获得与此有关的更多信息

我还想问一下multer-gridfs-storage如何使用gridfs-stream来存储文件,是否有规定规定在multer-gridfs-storage中应使用哪种流?

1 个答案:

答案 0 :(得分:0)

在这里,您将获得此视频教程的帮助 Uploading Files to MongoDB With GridFS (Node.js App) by Brad Traversy