Использование потока multer-gridfs в nestjs - PullRequest
0 голосов
/ 20 марта 2019

Я пытаюсь явно использовать промежуточное программное обеспечение multer-gridfs-storage в nestjs.Я хотел сохранить файл и получить его с помощью пакета gridfs-stream.Но у меня ничего не работает.Я не могу заполнить запрос самим файлом.Всякий раз, когда я пытаюсь напечатать объект запроса, он не имеет ничего общего с req.file или элементом буфера.И я не уверен, как обработать файл, как только получу его с помощью мультера.

Вот пример метода контроллера

@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 (узел: 29332). DeprecationWarning: collection.ensureIndex устарела. Вместо этого используйте createIndexes. (узел: 29332)1029 *

Следовательно, мы хотели использовать multer-gridfs-storage, который по умолчанию использует GridFSStorage

На всякий случай,Вот подробности о версии

"@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",

РЕДАКТИРОВАТЬ: Это для целей обучения и хотел иметь глубокое понимание того, как промежуточное программное обеспечение Express обрабатываются в Nestjs.Я понимаю, что nestjs имеет что-то вроде FileInterceptor для обработки файлов, но хотел бы получить больше информации об этом

Также я хотел бы спросить, как multer-gridfs-storage использует gridfs-stream для хранения файлов, есть лиположения о том, какой поток следует использовать в хранилище multer-gridfs?

1 Ответ

0 голосов
/ 27 марта 2019

здесь вы идете, это видео-руководство поможет вам Загрузка файлов в MongoDB с помощью GridFS (приложение Node.js) от Брэда Траверси

...